!
) prunes away part of the Prolog search-space. This
can be a very powerful mechanism for improving the performance of programs,
and even the suppression of unwanted solutions. However, it can also be
easily misused and over-used.
min(X,Y, Min) :- X <Y, Min = X. min(X,Y, Min) :- Y=<X, Min = Y. |
min(X,Y, Min) :- X<Y, !, Min = X. min(X,Y, Y). |
first_prime(X, P) :- prime(X,P), !. |
first_prime
returns the first prime number smaller than X
.
In this case, it calls a predicate prime/2
, which generates prime
numbers smaller than X
, starting from the largest one. The effect of
the cut here is to prune away all the remaining solutions to prime(X,P)
once the first one is generated, so that on backtracking, prime(X,P)
is not tried for alternative solutions. The cut will also commit the execution
to this clause for first_prime/2
, but as there is only one clause,
this has no visible effect.