Erlang hints for an OO junkie
Carsten Schultz
carsten@REDACTED
Tue Aug 10 20:03:02 CEST 2004
Hi!
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.
Greetings,
Carsten
--
Carsten Schultz (2:38, 33:47), FB Mathematik, FU Berlin
http://carsten.codimi.de/
PGP/GPG key on the pgp.net key servers,
fingerprint on my home page.
-------------- next part --------------
-module(queue).
-export([empty_list_queue/0,empty_okasaki_queue/0,
is_empty/1,in/2,out/1]).
list_empty() ->
[].
list_is_empty([]) ->
true;
list_is_empty([_|_]) ->
false.
list_in(X, L) ->
[X|L].
list_out(L) ->
[H|T] = lists:reverse(L),
{H, lists:reverse(T)}.
okasaki_empty() ->
{[], []}.
okasaki_is_empty({[], []}) ->
true;
okasaki_is_empty(_) ->
false.
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}) ->
(D#queue_dict.is_empty)(Q).
in(X, {D, Q}) ->
{D, (D#queue_dict.in)(X, 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: <http://erlang.org/pipermail/erlang-questions/attachments/20040810/9023f85b/attachment.bin>
More information about the erlang-questions
mailing list