% Example of evaluation % Suppose we represent an expression tree as a list: % % [Operator, LeftSubTree, RightSubTree] % % as required for the solve42 problem. % % Leaves of the tree are just numbers (non-lists) % % We can evaluate such a tree recursively using an 'eval' predicate as follows: eval(N, N) :- number(N). % A number is its own value. (number/1 is built-in) eval([Op, LeftTree, RightTree], Value) :- % Evaluate a tree recursively. eval(LeftTree, LeftValue), eval(RightTree, RightValue), evalOp(Op, LeftValue, RightValue, Value). % Separate evaluators for each operator: evalOp('+', A, B, R) :- R is A + B. % 'is' forces evaluation of RHS evalOp('*', A, B, R) :- R is A * B. evalOp('-', A, B, R) :- R is A - B. evalOp('/', A, B, R) :- B \== 0, R is A // B. % // is integer division % Tester testEval(Tree) :- eval(Tree, Value), write(Tree), write(' --> '), write(Value), nl. % Example test :- testEval(123), testEval([+, 56, 43]), testEval([-, 56, 43]), testEval([*, [+, 56, 43], [-, 56, 43]]), testEval([/, [*, [+, 56, 43], [-, 56, 43]], 3]).