[erlang-questions] Elixir Protocols in Erlang & a Strange Warning
Vincent Siliakus
zambal@REDACTED
Fri Dec 13 20:23:00 CET 2013
If you want to simulate Elixir's protocols in Erlang in a (arguably)
more idiomatic way, you could do something like this:
% Enumerable protocol API
-module(enumerable).
-export([behaviour_info/1, map/2]).
-callback map(F :: fun(), T :: any()) -> any().
map(F, T) ->
Mod = element(1, T),
Mod:map(F, T).
------------------------------------
% Enumerable protocol implementation 1
-module(mytype_1).
-export([new/1, map/2]).
-behaviour(enumerable).
-record(mytype_1, { list }).
new(List) ->
#mytype_1{ list = List }.
map(F, #mytype_1{ list = L }) ->
#mytype_1{ list = lists:map(F, L) }.
------------------------------------
% Enumerable protocol implementation 2
-module(mytype_2).
-export([new/1, map/2]).
-behaviour(enumerable).
-record(mytype_2, { array }).
new(List) ->
#mytype_2{ array = array:from_list(List) }.
map(F, #mytype_2{ array = A }) ->
#mytype_2{ array = array:map(fun(_I, X) -> F(X) end, A) }.
------------------------------------
1> T = mytype_1:new([1,2,3,4]).
{mytype_1, [1,2,3,4]}
2> enumerable:map(fun(X) -> X + X end, T).
{mytype_1, [2, 4, 6, 8]}
I didn't try to compile the above, so it may contain typo's, but I
guess you get the idea I'm getting at.
-vincent
More information about the erlang-questions
mailing list