Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define predicate in prolog programming?

Tags:

prolog

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?

like image 631
Alia Azmee Avatar asked Oct 31 '25 08:10

Alia Azmee


2 Answers

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.)

like image 74
Daniel Lyons Avatar answered Nov 02 '25 22:11

Daniel Lyons


This returns the min arguments of X&Y

min(X,Y,M):-
X<Y,!,M=X.
min(X,Y,M):-
M=Y.
like image 26
amjad khatabi Avatar answered Nov 03 '25 00:11

amjad khatabi