Prolog中失败谓词的用途是什么? [英] What are the uses of the fail predicate in Prolog?

查看:12
本文介绍了Prolog中失败谓词的用途是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想不出我需要它的情况.

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

推荐答案

优雅的系统提供 false/0 作为命令式 fail/0 的声明同义词.一个有用的示例是当您手动想要强制回溯以产生副作用时,例如:

Elegant systems provide false/0 as a declarative synonym for the imperative fail/0. An example where it is useful is when you manually want to force backtracking for side-effects, like:

?- between(1,3,N), format("line ~w
", [N]), false.
line 1
line 2
line 3

除了 false/0,您还可以使用任何失败的目标,例如短一点:

Instead of false/0, you can also use any goal that fails, for example a bit shorter:

?- between(1,3,N), format("line ~w
", [N]), 0=1.
line 1
line 2
line 3

因此,false/0 不是严格需要的,但非常好.

Thus, false/0 is not strictly needed but quite nice.

编辑:我有时会看到初学者想要声明例如我的关系不适用于空列表",然后添加:

EDIT: I sometimes see beginners who want to state for example "my relation does not hold for the empty list", and then add:

my_relation([]) :- false.

到他们的代码.这不是必要的,并且不是使用 false/0 的一个很好的例子,除了以编程方式生成的故障切片.相反,专注于陈述持有关于你们关系的事情.在这种情况下,只需省略整个子句,只为不为空的列表定义关系,即至少有一个元素:

to their code. This is not necessary, and not a good example of using false/0, except for example in failure slices that are programmatically generated. Instead, concentrate on stating the things that hold about your relation. In this case, just leave out the entire clause, and define the relation only for lists that are not empty, i.e., have at least one element:

my_relation([L|Ls]) :- 等等

或者,如果您还描述了列表之外的其他术语,请使用如下约束:

or, if you are describing other terms in addition to lists as well, use a constraint like:

my_relation(T) :- dif(T, []) 等

仅给出这两个子句中的一个(或两者),查询 ?- my_relation([]). 将自动失败.没有必要为此目的引入一个永远不会成功的附加条款.

Given only either (or even both) of these two clauses, the query ?- my_relation([]). will automatically fail. It is not necessary to introduce an additional clause which never succeeds for that purpose.

这篇关于Prolog中失败谓词的用途是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆