Skip to content

Instantly share code, notes, and snippets.

@darkf
Created August 31, 2012 07:24
Show Gist options
  • Select an option

  • Save darkf/3549865 to your computer and use it in GitHub Desktop.

Select an option

Save darkf/3549865 to your computer and use it in GitHub Desktop.
RPN calculator in Erlang
-module(rpn).
-export([eval/2, op/1, is_op/1, start/0]).
%% I hope I never have to touch Erlang again
op("+") -> fun(L,R) -> L+R end;
op("*") -> fun(L,R) -> L*R end.
is_op(X) -> X == "+" orelse X == "*".
eval([], Stack) -> Stack;
eval([Num|Rest], Stack) when is_integer(Num) ->
eval(Rest, [Num|Stack]);
eval([Cur|Rest], Stack) ->
case is_op(Cur) of
true ->
Rhs = hd(Stack),
Lhs = hd(tl(Stack)),
Res = apply(op(Cur), [Lhs, Rhs]),
eval(Rest, [Res|tl(tl(Stack))])
end.
start() ->
Res = eval([3, 2, "+", 2, "*", 2, "*"], []),
io:format("result: ~w~n", [Res]).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment