Saturday, October 25, 2008

A Stack in Erlang

I have been playing around with Erlang for a couple of weeks now. Its a really cool language and here's my first attempt at implementing a stack in it.

The basic design is to have process that gets different commands as messages, and updates the stack accordingly. Erlang being a functional language, implies that we cannot use an imperative approach. So, here's what the process looks like.

stack(S) ->
io:format("Stack:~p~n", [S]),
receive
{push, PID, Data} ->
PID ! success,
stack([Data|S]);
{pop, PID} ->
if
S == [] ->
PID ! failed,
stack(S);
true ->
[H|T] = S,
PID ! {success, H},
stack(T)
end

end.

Its pretty simple actually, but I did have a lot a trouble with push. Each push would create a list within a list, which meant that there could be only 2 pops. However, if we spawn stack with [] as that input parameter, then it works fine.

Next steps -> Get some more stack operations going. I'm going to implement a couple of functions - dup, swap, rot.

Technorati Tags:

No comments: