I'm looking for a way to build an Expression Tree in Prolog. I already did some experiments and came up with the following working code (that will only handle constants and the plus expression):
const(_).
plus(_, _).
eval(const(R), R).
eval(plus(A, B), R) :- number(A), number(B), R is A+B.
eval(plus(A, B), R) :- number(A), eval(B, B_R), R is A+B_R.
eval(plus(A, B), R) :- eval(A, A_R), number(B), R is A_R+B.
eval(plus(A, B), R) :- eval(A, A_R), eval(B, B_R), R is A_R+B_R.
Is there any simpler alternative to this approach? Will I have to define these 4 cases for each one of the operators I plan on adding to my program?
I think this should do it, though I'm not familiar with the construct
pred1(pred2(...)...) :- ...
(my Prolog is very rusty).See here another schema, exploiting DCG and (a kind of) lazy evaluation:
Using grammars to model data structures it's a very useful technique in Prolog. The grammar used it's an implementation of PEGs. Dependency from SWI-Prolog it's very limited, just number//1.