Skip to content

Instantly share code, notes, and snippets.

@gboncoffee
Created April 7, 2024 20:38
Show Gist options
  • Save gboncoffee/25fb2d3ef46f045eebb066de23b2ec78 to your computer and use it in GitHub Desktop.
Save gboncoffee/25fb2d3ef46f045eebb066de23b2ec78 to your computer and use it in GitHub Desktop.
Reverse polish calculator in Erlang
-module(calc).
-export([main_loop/1]).
read_tokens() ->
case io:get_line("calc> ") of
[] -> [];
L -> string:tokens(lists:droplast(L), " ")
end.
exec_token(S, T) ->
try
F = list_to_float(T),
[F|S]
catch error:badarg ->
{Fa, Fb, Tl} = {hd(S), hd(tl(S)), tl(tl(S))},
case T of
"+" -> [Fa + Fb|Tl];
"-" -> [Fa - Fb|Tl];
"*" -> [Fa * Fb|Tl];
"/" -> [Fa / Fb|Tl];
"clear" -> []
end
end.
exec_tokens(S, []) -> S;
exec_tokens(S, [T|R]) ->
exec_tokens(exec_token(S, T), R).
main_loop(S) when S =:= [] ->
main_loop(exec_tokens(S, read_tokens()));
main_loop(S) ->
io:format("~f~n", [hd(S)]),
main_loop(exec_tokens(S, read_tokens())).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment