Created
April 7, 2024 20:38
-
-
Save gboncoffee/25fb2d3ef46f045eebb066de23b2ec78 to your computer and use it in GitHub Desktop.
Reverse polish 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(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