4
votes

I am working with SWI Prolog. I wish to define an add function: add(X, Y) which returns the sum of X and Y. However, I do not know how to define functions in Prolog. I tried doing this using predicates as such:

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

but upon executing a query of the form add(2, 3, X) this gives an error saying:

ERROR: toplevel: Undefined procedure: add/3 (DWIM could not correct goal)

Also, I cannot understand the difference between :- and := while writing rules. I read somewhere that :- is used to define predicates while := is used to define functions. I am not sure if this is correct. I tried using := for defining functions but it doesn't work.

2

2 Answers

3
votes

Place yourself in the same directory as the prolog file, type the following to load and compile the source-file function.pl:

[function].

Now test run (with the exact code you posted in a file function.pl):

?- add(2,3,X).
X = 5.

Swi-prolog v 6.6.4 used.

Also, I cannot understand the difference between :- and := while writing rules. I read somewhere that :- is used to define predicates while := is used to define functions. I am not sure if this is correct. I tried using := for defining functions but it doesn't work.

A logic program is a set of axioms, or rules (aka predicates), defining relations between objects, the notion of explicit functions are not used but since a function really is just a mapping from a input-set to a output-set you can model it as a relation, just as you have done with the add/3 relation.

:- can be read as logical implication (and actually I think the symbol is supposed to look like the backwards arrow)

The := operator you are referring to I cannot even find in the swi prolog documentation: search results for :=. Would be great if you could link to where you found the information about it.

2
votes

To give the simplest answer I think the OP was looking for:

At the swipl / gprolog prompt:

?- [user].
add(X, Y, Z) :- Z is X+Y.
[control-D]

?- add(2,3,Answer).
Answer = 5

Explanation:

Prolog dates from the logic glory days of the 1980's and is designed around the command line. Entering "[foo]." at the command prompt (?-) means 'consult the file foo' i.e. load a Prolog program from the current directory in a file called 'foo.pl'. "[user]" is doing the exact same thing except 'user' is a reserved filename meaning stuff typed in by the user until they hit Control-D (the usual character representing end-of-file).