/*
 * There are several manners in which you can try to emulate object
 * orientation (OO) in Egel. This is one manner.
 *
 * An object has a mutable state and a collection of named methods. 
 */
import "prelude.eg"
// a namespace OO which introduces the 'object' datatype and 
// accessors.
namespace OO (
    using System
    data object
    def object_get_state =
        [ object STATE MM -> get STATE ]
    def object_set_state =
        [ object STATE MM, S -> object (set STATE S) MM ]
    def object_get_method0 =
        [ cons NAME0 (cons METHOD MM), NAME1 ->
            if NAME0 == NAME1 then METHOD else object_get_method0 MM NAME1
        | {}, NAME1 -> NAME1 ]
    def object_get_method =
        [ object STATE MM, NAME -> object_get_method0 MM NAME ]
    def @@ = 
        [ SELF, NAME -> (object_get_method SELF NAME) SELF ]
)
using OO
using System
// examples of a box and a circle class.
def box =
    [ W, H -> 
        object (var (W, H)) 
        { "resize", 
          [ SELF, WW, HH -> object_set_state SELF (WW, HH) ],
          "area",
          [ SELF -> [(W, H) -> W*H] (object_get_state SELF) ] }
    ]
def circle =
    [ R -> 
        object (var R) 
        { "resize", 
          [ SELF, R -> object_set_state SELF R ],
          "area",
          [ SELF -> [R -> (tofloat (R*R))*3 ] (object_get_state SELF) ] }
    ]
def main =
    B = box 1 5;
    AREA0 = B @@ "area";
    N = (B @@ "resize") 2 3;
    AREA1 = B @@ "area";
        (AREA0, AREA1)
It's good enough for now, I rather fix concurrency.
 
No comments:
Post a Comment