3
votes

Define the following predicate into a prolog program so that Min is the smaller of two numbers X and Y.

min (X, Y, Min)

Can you help me understand the question?

2
To give you a great answer, it might help us if you have a glance at How to Ask if you haven't already. - Mat
The question is asking you to write a Prolog predicate, min(X, Y, Min) which succeeds if Min is the minimum of the values X and Y (as stated in the question, Min is the smaller of the two numbers X and Y). - lurker

2 Answers

10
votes

In Prolog, we talk about predicates. In other languages you would probably call it a function, but in mathematics we are firm that a function associates a single value with the result of applying some formula to some other parameters to the function. That directionality does not hold in Prolog, so we call it a predicate or a relation.

The canonical solution to this problem is just this:

min(X, Y, Min) :- X =< Y, Min = X; Min = Y.

In Prolog, you always have a Horn clause, which has a head and a body. The head is what goes before the :- and names the predicate. The body is the list of expressions to the right of the :-. You should read this as "infer min(X, Y, Min) when X =< Y and Min = X, or else Min = Y". If the body of the clause is fulfilled, the head of the clause is inferred. In other words, if X =< Y and Min = X, then you could say min(X, Y, X) holds.

This says, essentially, if X =< Y, then Min is X; otherwise, Min is Y. It is probably more readably expressed with multiple clauses:

min(X, Y, X) :- X =< Y.
min(X, Y, Y) :- X > Y.

But this will create an unnecessary choice point; Prolog may think it has multiple solutions here even though you and I both know that X can only either be greater-or-equal to Y or less than Y. (We might inform Prolog of our awareness by using the cut operator, !, but it's overkill for this situation when you could just use conjunction and disjunction.)

2
votes

This returns the min arguments of X&Y

min(X,Y,M):-
X<Y,!,M=X.
min(X,Y,M):-
M=Y.