问题
can somebody please explain the processing of the following command:
max(X,Y,Max) :- X >= Y, !, Max = X ; Max = Y.
I can't understand, what exactly does it mean ! in the middle, thanks in advance
回答1:
The ! (cut) means if you got this far (successfully in the current goal), don't do any backtracking (consider alternative ways to satisfy the current goal) that might have been open before the cut's placement.
In your example the cut is being used to tersely express how to define the Max of X and Y. That is, once you succeed with the subgoal X >= Y, the right alternative is no longer in doubt (so unify Max with X).
The tricky thing here is the precedence of , (representing logical AND) and ; (representing logical OR). The latter binds more weakly than the former, so that the alternative subgoal unifying Max with Y can only be reached if X >= Y fails (the alternative for the current goal will not be considered if the cut is passed).
回答2:
I think the answered has been given quite clear.
Well, I just conclude a bit from your sample. Here, we can "assume" that there are two rules there, which are
max(X, Y, Max) :- X >= Y, !, Max = X.
max(X, Y, Max) :- Max = Y.
Why is it necessary to put that !? It is because without that, you can query something like max(5,4,Max) and the result would be
Max = 5;
Max = 4;
Why does it happen? Because Prolog system finds every possible answers. When the ! comes, it will stop finding the other(s).
来源:https://stackoverflow.com/questions/4769536/cut-processing-in-prolog