[erlang-questions] Elixir Protocols in Erlang & a Strange Warning

Richard A. O'Keefe ok@REDACTED
Wed Dec 18 02:58:41 CET 2013

On 17/12/2013, at 9:24 AM, Kaveh Shahbazian wrote:

> Not really; I did not want to simulate OO in Erlang (BTW Erlang feels perfectly OO to me; maybe in a very irrelevant way).
> I just used C# sample to convey something similar to what I wanted to do - which as I've mentioned in other email turned out to be a horrible sample.
> I wanted to do this:
> test(V) ->
>     X = ?protocolX(V),
>     X:act1(),
>     X:act2(),
>     % ...
>     X:actN(SomeArguments),
>     OtherThings().

Why is this X:act1() and not X:act1(V)?

Why not do it the way T did (sort of)?
That is, an "object" is a function which takes the name of
an operation as an argument and returns a function able to
carry it out.

There's a nasty little glitch in Erlang syntax;
instead of F(X)(Y) you have to write (F(X))(Y).
I'm not sure what the reason for this is.
However, here we go.

test(V) ->


1> F = fun (act1) -> fun () -> <<"foo">> end
         ; (act2) -> fun () -> <<"bar">> end
         ; (actN) -> fun (X) -> [<<"ugh">>,X] end
#Fun<erl_eval.6.13229925>2> (F(act1))().
3> (F(act2))().
4> (F(actN))(42).

You might prefer something like

5> H = fun (act1) -> <<"foo">>
         ; (act2) -> <<"bar">>
         ; ({actN,X}) -> [<<"ugh">>,X]
6> H(act1).
7> H(act2).
8> H({actN,42}).

Both of these possibilities can be handled by the
Dialyzer type system.  Effects still have to be
described in comments, alas.

More information about the erlang-questions mailing list