Reputation: 337
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!
Upvotes: 4
Views: 1480
Reputation: 3407
Although the answers by Tudor and gokhans deliver the wanted result, I think there is a more elegant solution.
The following will work in most Prolog implementations:
operation(X, Y, Operator, Result):-
Goal =.. [Operator, X, Y],
Result is Goal.
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.
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.
Upvotes: 5
Reputation: 210
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.
Upvotes: -3