[erlang-questions] Thinking in Erlang

Richard O'Keefe <>
Wed Apr 28 06:20:02 CEST 2010

On Apr 28, 2010, at 2:29 PM, David N Murray wrote:
[object creation in Lisp]

> What I'm realling doing above is encapsulating a mutable list and  
> carrying
> 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?

There may be two different questions lurking here,
and they have different answers.

(1) CAN you use gen_server to do this.
     Yes, of course.
(2) That's rather heavyweight compared with the simplicity of the
     Lisp version, do you HAVE to do that?
     No, you don't.

loop(State, N) ->
         {push,Item,Sender} ->
             loop(lists:sublist(State, 2, N-1) ++ [Item], N)
       ; {pop,Sender} when State =/= [] ->
             loop(tail(State), N)
       ; quit ->

push(Pid, Item) ->
     receive {ok,Pid} -> ok end.

pop(Pid) ->
     receive {here,Pid,Item} -> Item end.

quit(Pid) ->

new(N) when is_integer(N), N > 0 ->
     spawn(fun () -> loop([], N) end).

There are three relevant differences between Lisp and Erlang.
(1) Lisp has mutable data structures, Erlang doesn't.
(2) Erlang has lightweight processes, Lisp doesn't.
(3) Lisp has nested recursive functions, Erlang doesn't.

The "loop" function cannot be inside the "new" function
because it has to call itself, and Erlang has no LABELS form.

I would not be surprised to see that change some day.
Modules with parameters can be seen as an embarassingly
clumsy way to _sort of_ get nested functions, except in
that case it's the outer function that's crippled.

More information about the erlang-questions mailing list