This is a test review question that I am having trouble with. How do you write a method to evaluate an algebraic expression with the operators plus
,
minus
and times
. Here are some test queries:
simplify(Expression, Result, List)
?- simplify(plus(times(x,y),times(3 ,minus(x,y))),V,[x:4,y:2]).
V = 14
?- simplify(times(2,plus(a,b)),Val,[a:1,b:5]).
Val = 12
?- simplify(times(2,plus(a,b)),Val,[a:1,b:(-5)]).
Val = -8 .
All I was given were these sample queries and no other explanation. But I am pretty sure the method is supposed to dissect the first argument, which is the algebraic expression, substituting x and y for their values in the 3rd argument (List). The second argument should be the result after evaluating the expression.
I think one of the methods should be simplify(V, Val, L) :- member(V:Val, L).
Ideally there should only be 4 more methods... but I'm not sure how to go about this.
Start small, write down what you know.
is a perfectly good start:
(+ (* 4 2) (* 3 (- 4 2))) = 8 + 3*2 = 14
. But then, of course,is even better. Also,
all perfectly good Prolog code. But of course what we really mean, it becomes apparent, is
etc.
getVal/3
will need to retrieve the values somehow from theL
list, andcalculate/3
to actually perform the calculation, given a symbolic operation name and the list of calculated values.Study
maplist/3
and=../2
.(not finished, not tested).
OK,
maplist
was an overkill, as was=..
: all your terms will probably be of the formop(A,B)
. So the definition can be simplified toand the last possibility is,
x
ory
etc., that satisfyatom/1
.So the last call from the above clause could look like
retrieve(x,V,[x:4, y:3])
, or it could look likeretrieve(y,V,[x:4, y:3])
. It should be a straightforward affair to implement.