Saturday, March 11, 2017

Multi-methods in ELENA

In this tutorial I will show how multi-methods are implemented in ELENA

To take part in parameter dispatching classes should be declared with dispatchable attribute.

#subject value = MyValue.

dispatchable(value) class MyValue
{
}

To dispatch the parameter we have to send cast message to it:

class MyClass
{
    eval : o
    [
        o cast:%eval &to:$self.
    ]
    
    eval &value
    [
        console writeLine:"value".
    ]
}

This approach works quite good for a single parameter. For several parameters this approach works not so good. It is possible to resolve them using several nested closures. Currently general solution is not possible. But basic data types support limited two parameter dispatching:

dispatchable(value) class MyValue
{
    add : n : m
        = n cast:%add &and:m &to:$self.
        
    add &int:n &int:m
    [
        console writeLine:"int&int".
    ]        
        
    add &int:n &long:m
    [
        console writeLine:"int&long".
    ]        
        
    add &long:n &int:m
    [
        console writeLine:"long&int".
    ]        
        
    add &int:n &literal:m
    [
        console writeLine:"int&literal".
    ]        
        
    add &literal:n &int:m
    [
        console writeLine:"literal&int".
    ]        
        
    add &char:n &int:m
    [
        console writeLine:"char&int".
    ]        
        
    add &int:n &char:m
    [
        console writeLine:"int&char".
    ]        
}

symbol program =
[
    var o := MyClass new.
    
    o add:1:2.
    o add:1:2l.
    o add:1l:2.
    o add:1:"string".
    o add:"string":2.
    o add:#32:2.
    o add:1:#32.
].

The result will be:

int&int
int&long
long&int
int&literal
literal&int
char&int
int&char

No comments:

Post a Comment