# Prefix expression evaluation in Prolog

A friend of mine this morning asked me to program Prolog to evaluate [+, +, /, 1, 2, *, 5, 6, 7] and return X as the output with X’s value equals 1 / 2 + 5 * 6 + 7. I do not know her motivation behind this question still I find it interesting so I have spent roughly 2 hours on this stuff. It was fun so I decide to post the solution on here:

1 2 3 4 5 |
eval(X, [X|D], D) :- number(X). eval(X, [+|T], D) :- eval(A, T, D1), eval(B, D1, D), X is A+B. eval(X, [-|T], D) :- eval(A, T, D1), eval(B, D1, D), X is A-B. eval(X, [*|T], D) :- eval(A, T, D1), eval(B, D1, D), X is A*B. eval(X, [/|T], D) :- eval(A, T, D1), eval(B, D1, D), X is A/B. |

Ex: eval(X, [+, +, /, 1, 2, *, 5, 6, 7], []).