Define the following predicate into a prolog program so that
Minis the smaller of two numbersXandY.
min (X, Y, Min)
Can you help me understand the question?
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.)
This returns the min arguments of X&Y
min(X,Y,M):-
X<Y,!,M=X.
min(X,Y,M):-
M=Y.
min(X,Y,Y) with no guard. Relying on the cut in another clause to supply correctness makes me shudder. Presumably @false can demonstrate a way to trip over backwards correctness; this is an area where I can now smell the problem but still can't reliably produce the effect of it. Essentially what it means is that if you hit something later in the query that causes you to reconsider a choice point, you could be backed into a clause unexpectedly.
min(X, Y, Min)which succeeds ifMinis the minimum of the valuesXandY(as stated in the question,Minis the smaller of the two numbersXandY).