Arithmetic operator as an argument

Assume I want to write calculator.
Is there any way to use the arithmetic operator as an argument
like this:

opp(A, B, Op, Res) :- Op(A, B, Res))

opp(1, 2, +, Res)

This is going to be 10x more complicated than what you ask, but because it is 10x more complex and works you should take that to mean that this is a valid way to do it.

Look at this code: https://github.com/maths/PRESS/blob/026ff5d5e2a572fd05e4313792a177dab6682660/util/tidy.pl

that is part of PRESS: PRolog Equation Solving System

1 Like

Hi

    	 moraneus 

September 9
Assume I want to write calculator.
Is there any way to use the arithmetic operator as an argument
like this:

opp(A, B, Op, Res) :- Op(A, B, Res))

opp(1, 2, +, Res)

I don’t know. But you could encapsulate the operator in a predicate.
Like this (untested):

plus(A, B, C) :-
   C is A+B.

opp(A, B, Op, C) :-
   call(Op, A, B, C).

opp(1,2,plus,Res)

Bye
Volker

1 Like

One clean approach that works for arithmetic is to make an expression that you then evaluate using is/2. Like this:

opp(A, B, Op, R) :-
    Expr =.. [Op, A, B],
    R is Expr.

With this I get:

?- opp(1, 2, +, R).
R = 3.

?- opp(1, 2, *, R).
R = 2.

?- opp(1, 2, -, R).
R = -1.

?- opp(1, 2, /, R).
R = 0.5.
2 Likes

This 100 times more complicated :slight_smile:

1 Like