I am trying to write a predicate that returns the minimum and maximum between two numbers.
The min and max predicates work fine, however when I try the min_max function with for example min_max(2,5,X,Y), I get false.
Can anyone help?
min(X,Y,X) :- X=<Y.
min(X,Y,Y) :- Y<X.
max(X,Y,Y) :- X=<Y.
max(X,Y,X) :- Y<X.
min_max(X,Y,MIN,MAX) :-
min(X,Y,MIN),
max(X,Y,MAX).
Your
min/2andmax/2are indeterminate, so there are alternatives to be looked for. When you evaluateYou see
and it pauses, waiting for input from you. If you then press
., it will succeed. If, however, you press;it searches for the alternatives, and finding none, fails.You need to modify your
min/2andmax/2to be determinate, something like this:[The
->operator (implication) effectively acts as a 'soft cut', eliminating alternatives.]Once you do that, it will work as you might expect, without pausing for your input (as you've eliminated the choice points):
It might help if you think of the your prolog program as something of a tree with the choice points as branches (and solutions as leaf nodes). The prolog engine runs over that tree trying to find solutions.
In your original program, your
min_max/4has 4 possible solutions (2 formin/2and 2 formax/2), even though there is just one "functional" solution. On backtracking, the prolog engine trys to find alternative solutions and finding none, fails.By re-writing
min/2andmax/2to eliminate the choice points, we are effectively pruning the tree as we descend it, leaving us with a single solution.