Thursday, February 9, 2017

Mixins in ELENA : State machine

In this tutorial we will see how to program a simple state machine using Mixins and message dispatching.

Let's just remember that a generic message in ELENA can be qualified.

   class MyClass
   {
       eval
       [
          console writeLine:"generic eval method"
       ]                                                    

       state0'eval
       [
          console writeLine:"qualified state0'eval method"
       ]
   }

   symbol program =
   [
      var o := MyClass new.

      var subj := %state0.  // a subject - message qualified

      o eval.                // output : generic eval method.

      o::subj eval          // output : qualified state0'eval method.
   ].

"subj" is a subject class which qualifies the generic message "eval". In the expression "o::subj" we create a temporal mixin object (so called a temporal mutation). As a result "eval" message is turned into state0'eval and is sent to the instance of MyClass.

This principle will help us to create our simple state machine.

class Statemachine
{
    object theState.
    
    set
        => theState.
    
    set &state0
    [
        console writeLine:"set&state0".
        
        theState := %state1.
    ]

    set &state1
    [
        console writeLine:"set&state1".
        
        theState := %state0.
    ]
        
    constructor new
    [
        theState := %state0.
    ]
}
                                                      
symbol program =
[
    var o := Statemachine new.
    
    o set. // output : set&state0
    o set. // output : set&state1
    o set. // output : set&state0
    o set. // output : set&state1
].

The key element is a message dispatching expression:

    set
        => theState.

This code is equivalent to our mutation expression:

    set
        = self::theState set.

As a result we create a state machine without branching operators, using only ELENA dispatching routines.