Too much backtracking: why is there a “redo” here?

前端 未结 2 1013
栀梦
栀梦 2021-01-21 14:57

I\'m doing a very simple exercise in Prolog and there\'s something I don\'t understand in the trace. The program is a \"greater than\" (>) on integers represente

2条回答
  •  粉色の甜心
    2021-01-21 15:54

    There reason there is a redo is that prolog cannot deduce (without examining it) if, by following the next clause, there would be an alternative solution. True, in this case it is just one head unification check (not that this is always trivial) but it could be something that could take a lot of time (or even never terminate).

    Now, this is exactly where you should use cut: you know that the extra choice points wont produce a solution (so you are not changing the semantics - a green cut). Alternatively (but it's mostly syntactic sugar covering a cut) you can use if-then-else:

    greater_than(succ(A), B):-
        B = succ(BI) ->
        greater_than(A,BI)
        ; B = 0.
    

    not that this still does extra computations which would be avoided with cut.

    PS: I doubt that anyone would think it's homework XD

提交回复
热议问题