What are the uses of the fail predicate in Prolog?

前端 未结 4 1347
南笙
南笙 2020-12-03 21:22

I can\'t come up with a situation where I would need it.

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-03 21:49

    Explicit failure. fail is often used in conjunction with cut: ... !, fail. to enforce failure.

    For all construct. Explicit usage of fail/false to enumerate via backtracking is a very error prone activity. Consider a case:

    ... ( generator(X), action(X), fail ; true ), ...
    

    The idea is thus to "do" action for all X. But what happens, if action(X) fails? This construct simply continues with the next candidate — as if nothing happened. In this manner certain errors may remain undetected for very long.

    For such cases it is better to use \+ ( generator(X), \+ action(X) ) which fails, should action(X) fail for some X. Some systems offer this as a built-in forall/2. Personally, I prefer to use \+ in this case because the \+ is a bit clearer that the construct does not leave a binding.

    Failure-slice. For diagnostic purposes it is often useful to add on purpose false into your programs. See failure-slice for more details.

提交回复
热议问题