I'm learning Prolog and I'm having some difficulties to understand how this particular operator works. I've been told it's used to stop backtracking during recursivity, but I can't quite picture it. What would be an example in a non-declarative language like Java? Maybe if I find a parallel I'm used to I'll be able to understand it.
Thank you!
The cut (
!/0
) doesn't "stop backtracking": it simply eliminates a choice point. Consider something like this,For any odd integer, it has a single solution:
odd
. But for any even integer, it has two solutions: it will first identify aseven
, and on backtracking, identify asodd
.An integer's being even or odd is deterministic:
4
is not going to beeven
on first evaluation, and then magically becomeodd
on reevaluation.So, we introduce a cut to eliminate the choice point(s)/alternative(s):
Now, having made the determination that
X
is even, the cut eliminates the choice point, and essentially "prunes" the search tree: backtracking into the cut causes the entire containing predicate to fail (and continue backtracking through the solution tree).