为什么我的 replace/2 程序总是返回 false? [英] Why does my replace/2 program always return false?

查看:56
本文介绍了为什么我的 replace/2 程序总是返回 false?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是用给定列表中的逻辑变量替换 '_'.我的代码:

My goal is to replace the '_' with logic variables in a given list. My code:

replace([], []).
replace(['_'|As], [_|Bs]) :- 
    replace(As, Bs).
replace([A|As], [B|Bs]) :-
    A \= '_',
    B = '#',
    replace(As, Bs).

它将返回一个正确的列表,但总是以 false 结束.有什么帮助吗?

It will return a proper list but always ends up with false. Any help please?

推荐答案

任何匹配 replace(['_'|As], [_|Bs]) 的输入,也匹配 替换([A|As], [B|Bs]).这意味着在执行第一个子句时,为后一个子句留下了一个选择点.

Any input that matches replace(['_'|As], [_|Bs]), also matches replace([A|As], [B|Bs]). This means that while the first clause is executed, a choice point is left for the latter one.

prolog 找到第一个结果后,注意到还有选择点打开,所以它会问你是否想要更多的结果.如果你说是,它不会尝试执行另一个子句.这将始终失败,因为 A \= '_' 永远不会为真.

After prolog has found the first result, it notices that there are still choice points open, so it will ask you if you want more results. If you say yes, it will not try to execute the other clause. This will always fail, since A \= '_' is never true.

请注意,这种行为并没有错.'false' 并不意味着程序失败,它只是意味着在那些已经呈现的结果之后没有找到更多的结果.在这种情况下,您知道始终只有一个结果,因此您可以使用切割运算符 ! 告诉 prolog 不要让任何选择点保持打开状态,如下所示:

Note that this behavior is not wrong. The 'false' doesn't mean that the program failed, it just means that no more results were found after those that had already been presented. In this case, you know that there will always only be one result, so you can tell prolog not to leave any choice point open by using the cut operator ! like this:

replace(['_'|As], [_|Bs]) :- 
    replace(As, Bs), !.

这本质上是告诉序言,如果这个子句成功了,剩下的可能匹配就不再考虑了.因此,没有选择点是开放的,一旦你得到第一个结果,执行就完成并返回 true.

This essentially tells prolog that if this clause succeeded, the remaining possible matches should no longer be considered. As such, no choice points are left open, and once you get the first result, the execution is done and returns true.

这篇关于为什么我的 replace/2 程序总是返回 false?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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