简体   繁体   中英

How to define predicate in prolog programming?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM