Erlang hints for an OO junkie

Carsten Schultz <>
Tue Aug 10 20:03:02 CEST 2004


On Tue, Aug 10, 2004 at 08:34:19PM +0400, Vlad Balin wrote:
> It's just fine, we succeed, we have a "class" queue defined now,
> with a number of "methods".  But here is one problem remains.
> Suppose we have defined another implementation of queue with a same
> interface.  How would we define a generic function working with both
> implementation then?
> Problem is that we supposed not to have derect access to the data structure
> of the abstract data type, so we need operations to be _polymorphic_.
[solution snipped]

I am not advocating this in any way, but you could also use a style
like in the appended module, if you really have to.



Carsten Schultz (2:38, 33:47), FB Mathematik, FU Berlin
PGP/GPG key on the key servers, 
fingerprint on my home page.
-------------- next part --------------


list_empty() ->

list_is_empty([]) ->
list_is_empty([_|_]) ->

list_in(X, L) ->

list_out(L) ->
    [H|T] = lists:reverse(L),
    {H, lists:reverse(T)}.

okasaki_empty() ->
    {[], []}.

okasaki_is_empty({[], []}) ->
okasaki_is_empty(_) ->

okasaki_in(X, {In, Out}) ->
    {[X|In], Out}.

okasaki_out({In, [X|Out]})->
    {X, {In, Out}};
okasaki_out({In, []}) ->
    [X|Out] = lists:reverse(In),
    {X, {[], Out}}.

-record(queue_dict, {is_empty, in, out}).

make_gen_queue(Empty, Is_Empty, In, Out) ->
    {#queue_dict{is_empty=Is_Empty, in=In, out=Out}, Empty()}.

empty_list_queue() ->
    make_gen_queue(fun list_empty/0, fun list_is_empty/1, 
		   fun list_in/2, fun list_out/1).

empty_okasaki_queue() ->
    make_gen_queue(fun okasaki_empty/0, fun okasaki_is_empty/1, 
		   fun okasaki_in/2, fun okasaki_out/1).

is_empty({D, Q}) ->

in(X, {D, Q}) ->
    {D, (, Q)}.

out({D, Q}) ->
    {O, Q0} = (D#queue_dict.out)(Q),
    {O, {D, Q0}}.

-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: not available
URL: <>

More information about the erlang-questions mailing list