a13e
a13e

Reputation: 928

Returning a value from a function in prolog

How do we return a value from a Prolog function that takes only one argument? Ex. leaf(V) is a function which should return a value V and it is called from a function tree(leav(V), sum)?

Upvotes: 7

Views: 26208

Answers (2)

Tasos Papastylianou
Tasos Papastylianou

Reputation: 22215

Prolog doesn't have "functions", it has "predicates". I.e. they are a description of a relationship between terms. A predicate can only evaluate to "true" or "false".

However, the way a predicate evaluates to true or false is by unification, i.e. prolog tries to find instances for the variables from the existing knowledge base (i.e. your source code) that will make that predicate true.

Therefore you can trick a prolog predicate of the form Pred(In, Out), such that, for a given "In" prolog could unify "Out" with the right value that makes the predicate true.

Upvotes: 8

David Tonhofer
David Tonhofer

Reputation: 15316

Prolog does not have function evaluation, so you will have to represent your function as a relation

f(In,Out) :- ... define the relationship between In and Out in the body ...

For example for squaring:

square(X,Y) :- Y is X*X.
?- square(12,X).
X=144

The "function symbols" in Prolog are purely denotational: they are for constructing terms:

f(x)

The above term has no inherent meaning or resolvability. It is just a term, more precisely a tree

f
|
x

Upvotes: 7

Related Questions