Skip to content

Instantly share code, notes, and snippets.

@kkweon
Created November 12, 2024 08:45
Show Gist options
  • Save kkweon/04dd675b63908043d38e7743ade51aa2 to your computer and use it in GitHub Desktop.
Save kkweon/04dd675b63908043d38e7743ade51aa2 to your computer and use it in GitHub Desktop.
#!/usr/bin/env swipl
:- use_module(library(dcg/basics)).
:- use_module(library(main)).
:- initialization(main, main).
expression(Value) --> term(V1), whites, expression_tail([V1], Value).
expression_tail(Stack, Value) -->
term(NewValue), { NewStack = [NewValue|Stack] }, whites, expression_tail(NewStack, Value).
expression_tail(Stack, Value) -->
operator(Op),
{ Stack = [V2,V1|RestStack], do_op(Op, V1, V2, Result), NewStack = [Result|RestStack] },
whites,
expression_tail(NewStack, Value).
expression_tail([Value], Value) --> [].
term(Value) --> number(Value).
operator(plus) --> "+".
operator(minus) --> "-".
operator(times) --> "*".
operator(div) --> "/".
do_op(plus, V1, V2, Result) :- Result is V1 + V2.
do_op(minus, V1, V2, Result) :- Result is V1 - V2.
do_op(times, V1, V2, Result) :- Result is V1 * V2.
do_op(div, V1, V2, Result) :- Result is V1 / V2.
main(_) :-
% Read single line from pipe or terminal
read_line_to_string(current_input, Line),
(Line = end_of_file ->
halt(0)
;
string_codes(Line, Codes),
(phrase(expression(Result), Codes) ->
format('~w~n', [Result]),
halt(0)
;
format('Invalid expression~n', []),
halt(1)
)
).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment