Question

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

So, this 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 probably guess, Prolog cannot identify Op as an arithmetic operation. Does anyone have an idea how this is possible?

I could not find anything on the internet yet, even though it is rather basic, I think.

Thanks in advance!

Was it helpful?

Solution

Although the answers by Tudor and gokhans deliver the wanted result, I think there is a more elegant solution.

Portable solution

The following will work in most Prolog implementations:

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

Extended but SWI-Prolog specific solution

SWI-Prolog allows the definition of custom arithmetic functions. The following code extends the above for use with such user-defined functions coming from other modules:

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

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

Notice that support for user-defined functions is deprecated in SWI-Prolog and does not work in other Prologs that do not have this feature.

Usage examples

Some examples of using these implementations of 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.

OTHER TIPS

You need to tell Prolog if Op is '+' then sum X and Y. You can do that as following

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

You can increase number of operations.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top