Created
August 31, 2012 07:24
-
-
Save darkf/3549865 to your computer and use it in GitHub Desktop.
RPN calculator in Erlang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| -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