farzad
farzad

Reputation: 53

Custom Prolog arithmetic function

I'm looking for something like built-in arithmetic operators that has a return value in Prolog (specifically in SWI-Prolog). E.g. if you run A is (1+2) + (3+2)., it returns A = 8..

How can I define func operator to do something like + operator?
E.g. A is (2 func 3) func (4 func (2+1))..

Upvotes: 5

Views: 2967

Answers (2)

user206428
user206428

Reputation:

In order to situate your function func inline just as the + operator (along with many others), you'll need to define a precedence order for func and it's arguments. You can achieve this in SWI-PROLOG with op/3.

For example, the directive (preceding code where func/2 is used):

:- op(500,yfx,func).

To implement func/2, you can either write a meta-interpreter for your language (i.e., you write a PROLOG program which parses term expressions including func and interprets them as you wish), or if func/2 is strictly arithmetic, you can use arithmetic_function/1 also as a directive, as follows:

:- arithmetic_function(func/2).

Testing this with the following definition for func/2:

func(X, Y, Z) :- 
    Z is X + Y.

Gives, with your example:

?- A is (2 func 3) func (4 func (2+1)).
A = 12.

Upvotes: 7

I GIVE CRAP ANSWERS
I GIVE CRAP ANSWERS

Reputation: 18869

It is in the manual, arithmetic_function/1 will raise your relation into something which is can understand, see

http://www.swi-prolog.org/pldoc/doc_forobject=section(2,'4.26',swi('/doc/Manual/extendarith.html'))

Upvotes: 2

Related Questions