[erlang-questions] Thinking in Erlang

Johan Montelius johanmon@REDACTED
Wed Apr 28 11:39:13 CEST 2010


> it around inside the function, hidden from the user.  If I try and
> implement something like this in Erlang, and don't want to be passing
> the list around to whomever may use it, I'm doing it with a gen_server,
> correct?

You could try something like this but the process way described by Richard  
O'Keefe is of course the Erlang way of doing it.

   Johan

8<----------------------------------------
-module(fqueue).

-export([new/1, push/2]).

new(N) -> fun(Elm) ->  push(Elm, N, []) end.
		
push(Queue, Element) ->
     Queue(Element).

push(Element, N, All) ->
     Popped = pop([Element|All], N),
     fun(Elm) -> push(Elm, N, Popped) end.

pop(All, N) ->
     if length(All) > N ->
	    {Rest, Pop} = lists:split(N, All),
	    io:format("popping ~w~n", [Pop]),
	    Rest;
        true ->
	    All
     end.

8<----------------------------------------

24> Q0 = fqueue:new(2).
#Fun<fqueue.0.52719240>
25> Q1 = fqueue:push(Q0, foo).
#Fun<fqueue.1.51420881>
26> Q2 = fqueue:push(Q1, bar).
#Fun<fqueue.1.51420881>
27> Q3 = fqueue:push(Q2, zot).
popping [foo]
#Fun<fqueue.1.51420881>
28>





-- 
Dr Johan Montelius
Royal Institute of Technology - KTH
School of Information and Communication Technology - ICT


More information about the erlang-questions mailing list