Reputation: 1
I am doing an arithmetic expression in prolog. the predicate is like expression(expr, _Val, _Var, N). If I test
?-expression(y*(1+y*y),3,y,R)
the result would be
R=30
It work find. But if I want to test
?- expression(x*(1+y*y),3,y,R)
the result would be
R=x*10
But it is does not work for me. It seems like I have to test the term N whether it is a number or an atom. if number it will compute otherwise it the case should be left as is in output R=x*10 I am glad if someone could help me.
the code is something like this:
type(N) :-
functor(N,_,_),
number(N).
expression(V,Val,V,Val).
expression(expr, Val, _Var, N).
expression(N, _Var, _Val, N) :-
type(N).
expression(A*B, Var,Val, R) :-
expression(A, Var, Val, RA),
expression(B, Var, Val, RB),
R is RA*RB.
expression(A+B, Var,Val, R) :-
expression(A, Var, Val, RA),
expression(B, Var, Val, RB),
R is RA+RB.
Upvotes: 0
Views: 79
Reputation: 60004
this
expression(expr, Val, _Var, N).
seems completely useless. It's part of 'specification space', not 'solution space', just to say.
Before evaluating by means of is/2, you should check if the recursively evaluated subexpressions are numeric:
expression(A+B, Var,Val, R) :-
expression(A, Var, Val, RA),
expression(B, Var, Val, RB),
( number(RA), number(RB) ->
R is RA+RB
; R = RA+RB
).
Upvotes: 1