-1

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!

false
  • 10,264
  • 13
  • 101
  • 209
jack
  • 9
  • 2
  • It has nothing to do with recursivity. And in Java, there is no backtracking-search. See [tag:prolog-cut] for more. – false May 09 '22 at 10:24

1 Answers1

0

The cut (!/0) doesn't "stop backtracking": it simply eliminates a choice point. Consider something like this,

even_or_odd( X , even ) :- 0 =:= X mod 2 .
even_or_odd( _ , odd  ) .

For any odd integer, it has a single solution: odd. But for any even integer, it has two solutions: it will first identify as even, and on backtracking, identify as odd.

An integer's being even or odd is deterministic: 4 is not going to be even on first evaluation, and then magically become odd on reevaluation.

So, we introduce a cut to eliminate the choice point(s)/alternative(s):

identify_even_or_odd( X , even ) :- 0 =:= X mod 2 , ! .
identify_even_or_odd( _ , odd  ) .

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

Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135