问题
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