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 eval message in ELENA can be qualified (e.g. dispatched with a subject).

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

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

   symbol program =
   [
      var o := MyClass new.

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

      o eval.                // output : generic eval method.

      o~subj eval          // output : qualified state0 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[0]" message is turned into "state0[0]" and is sent to the instance of MyClass.

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

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

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

The key element is a message dispatching expression:

    eval
        => theState.

This code is equivalent to our mutation expression:

    eval
        = self~theState eval.

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

4 comments:

  1. Damn... why I'm not young and enthusiastic? I'd like your language very much then. It really looks interesting.

    What about performance? How it compares to Ruby, for example?

    ReplyDelete
  2. Thanks :)

    I did not make any benchmarks but I tried really hard to improve performance (using direct method call when possible, stack allocating and so on).

    Of course Ruby has better GC than my language. I cannot compete with the whole community :)

    ReplyDelete
  3. Updated to be compatible with ELENA 3.0

    ReplyDelete
  4. Updated to be compatible with ELENA 3.2

    ReplyDelete