Dynamic arithmetic expression Prolog

I am new to Prolog and would like to define a simple predicate that calculates the result depending on which function I choose to use in an arithmetic expression.

So that was my idea:

operation(X,Y, Op, Result):-
  Result is X Op Y.

Now I was expecting this from Prolog:

operation(3,4,'+', X).
X = 7.

But, as you can guess, Prolog cannot be identified Opas an arithmetic operation. Does anyone have an idea how this is possible?

I could not find anything on the Internet, although I find it quite simple.

Thanks in advance!

+4
source share
2 answers

Although the answers of Tudor and Gohan give the desired result, I think there is a more elegant solution.

Portable solution

Prolog :

operation(X, Y, Operator, Result):-
  Goal =.. [Operator, X, Y],
  Result is Goal.

, SWI-Prolog

SWI-Prolog . , :

:- meta_predicate(operation(+,+,2,-)).

operation(X, Y, Module:Operator, Result):-
  Goal =.. [Operator, X, Y],
  Module:(Result is Goal).

, SWI-Prolog , .

operation/4:

?- operation(1, 2, mod, X).
X = 1.

?- operation(1, 2, //, X).
X = 0.

?- operation(1, 2, /, X).
X = 0.5.

?- operation(1, 2, -, X).
X = -1.

?- operation(1, 2, +, X).
X = 3.
+4

, Op - "+", X Y. ,

operation(X,Y, Op, Result) :- 
   Op = '+',  
   Result is X + Y
 ;
   Op = '-',  
   Result is X - Y.

.

-3

Source: https://habr.com/ru/post/1535881/


All Articles