
Use State Machines - AndrewKemendo
https://rclayton.silvrback.com/use-state-machines
======
neilv
Here's one way to do implement a simple state machine like this in Scheme,
with a procedure representing a state, and using tail calls (function calls
that don't return) for the transitions:

    
    
      (define (order-creating-state)
        (let loop-within-state ()
          (let ((event (get-event)))
            (case (event-type event)
    
              ((add-item)
               (add-item-to-order (event-data event))
               (loop-within-state))
    
              ((delete-item)
               (delete-item-from-order (event-data event))
               (loop-within-state))
    
              ((finalize)
               (order-finalizing-state))
    
              (else (error "order-creating-state: invalid event"))))))
    

In Scheme you could also decide on your state model, and make the code more
maintainable in terms of that state model, by defining a minilanguage or
domain-specific language for it:

    
    
      (state order-creating (event)
             (add-item    (add-item-to-order event))
             (delete-item (delete-item-from-order event))
             (finalize    (transition-to order-finalizing)))

