Prolog - a variable as an operator

I have an operator stored in the variable Op, and two integers are stored in X and Y. Now I want to do something like (Z is X Op Y), but this syntax seems to be wrong.

Does anyone know if there is a way to do this in Prolog?

thank you for your responses

+4
source share
2 answers

you can do this by constructing a predicate using the = operator ..

try:

compute(X,Y,Op,Z) :- Eq=..[Op, X, Y], Z is Eq. 

The operator is really the same as any other functor.

+8
source

You can simulate the effect:

 operator(Z,X,plus,Y):-Z is X + Y. operator(Z,X,times,Y):-Z is X * Y. 

I tried this on ideone.com for SWI-Prolog with:

 OP=times, operator(Z,3,OP,8). 

And I got:

 OP = times, Z = 24. 
0
source

All Articles