efene programming language

a gen_server behavior in efene

to show the status of efene and show that it can be used for complex and real life thing I decided to port a random gen_server example to efene (in this case ifene).

I did a search for “erlang behavior example” and picked a useful example, in this case this post seemed interesting:

http://20bits.com/articles/erlang-a-generic-server-tutorial/

you can see the original code there, the translated code:

@@author("Jesse E.I. Farmer <jesse@20bits.com>")
@@behaviour(gen_server)

# These are all wrappers for calls to the server
@public
start = fn ()
    gen_server.start_link((local, $module), $module, [], [])

@public
checkout = fn (Who, Book)
    gen_server.call($module, (checkout, Who, Book))

@public
lookup = fn (Book)
    gen_server.call($module, (lookup, Book))

@public
return = fn (Book)
    gen_server.call($module, (return, Book))

# This is called when a connection is made to the server
@public
init = fn ([])
    Library = dict.new()
    (ok, Library)

# handle_call is invoked in response to gen_server.call
@public
handle_call = fn ((checkout, Who, Book), _From, Library)

    Response = if dict.is_key(Book, Library)
        NewLibrary = Library
        (already_checked_out, Book)
    else
        NewLibrary = dict.append(Book, Who, Library)
        ok

    (reply, Response, NewLibrary)

fn ((lookup, Book), _From, Library)

    Response = if dict.is_key(Book, Library)
        (who, lists.nth(1, dict.fetch(Book, Library)))
    else
        (not_checked_out, Book)

    (reply, Response, Library)

fn ((return, Book), _From, Library)

    NewLibrary = dict.erase(Book, Library)
    (reply, ok, NewLibrary)

fn (_Message, _From, Library)

    (reply, error, Library)

# We get compile warnings from gen_server unless we define these
@public
handle_cast = fn (_Message, Library)
    (noreply, Library)

@public
handle_info = fn (_Message, Library)
    (noreply, Library)

@public
terminate = fn (_Reason, _Library)
    ok

@public
code_change = fn (_OldVersion, Library, _Extra)
    (ok, Library)

I just made the translation and compiled it, it compiled without problem, then I tried the commands that were in the original post:

mariano@ganesha:~$ fnc library.ifn
Compiling library.ifn
mariano@ganesha:~$ erl
Erlang R13B03 (erts-5.7.4) [source] [rq:1] [async-threads:0] [hipe] [kernel-poll:false]

Eshell V5.7.4  (abort with ^G)
1> library:start().
{ok,<0.37.0>}
2> library:checkout(jesse, "American Creation").
ok
3> library:lookup("American Creation").
{who,jesse}
4> library:checkout(james, "American Creation").
{already_checked_out,"American Creation"}
5> library:return("American Creation").
ok
6> library:checkout(james, "American Creation").
ok

everything worked as expected.

nice :)


To Tumblr, Love Metalab