Rob L
Rob L

Reputation: 3303

How to return two values from a basic predicate(?) in Prolog?

I just started going over Prolog about an hour ago and have already stumbled into a slight problem I am unsure about. I am writing a predicate (or function?) that takes a list and returns the min and max values. Right now, I am just looking at one of the special cases when the list has 1 item. For example, if you query minmax([5], X, Y). I want the predicate to return X=5 Y=5. I have this code:

minmax([X], X, X). 

but it is returning X = Y, Y = 5. I know it is a true statement and trivial, but is there a way I can return X=5,Y=5 ???

Upvotes: 0

Views: 672

Answers (2)

Nicholas Carey
Nicholas Carey

Reputation: 74177

It is returning what you think it is. X is 5 as is Y. The values are unified and so the interpreter shows the message X=Y, Y=5. You need to get out the Prolog textbook and read up on unification of terms.

You could just as easily say

foo(A,B) :- A = 5 , B is (A+A)/2 .

and query it:

?- foo(X,Y).

and get the same result. In the Prolog universe, there is only ever a single instance of the integer 5.

Upvotes: 2

Fred Foo
Fred Foo

Reputation: 363487

X=Y, Y=5 means that X and Y are now both equal to 5. It's just a different way of saying that; you really shouldn't care. If you print both values, you'll just get 5:

?- [user].
|: print_stuff :-
|:   X = Y,
|:   Y = 5,
|:   write('X = '), writeln(X),
|:   write('Y = '), writeln(Y).
|: % user://1 compiled 0.02 sec, 2 clauses
true.

?- print_stuff.
X = 5
Y = 5
true.

Upvotes: 1

Related Questions