Why does my replace/2 program always return false?

有些话、适合烂在心里 提交于 2019-12-11 17:33:47

问题


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

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


回答1:


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.

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.

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

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.



来源:https://stackoverflow.com/questions/26459971/why-does-my-replace-2-program-always-return-false

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!