Prolog - 找到第一个解决方案并停止搜索

Chr*_*her 6 prolog

我正在 Prolog 中学习编程并且有一个规则问题,它必须搜索解决方案,一旦找到,它必须“什么都不做”。但它失败了,给了我不止一种解决方案。我试图做这样的事情:

% here the solution is already found and there's nothing to be done.
findsolution:-
       solution(X).

% trying to find the solution and use assert/1 if it was found. 
 findsolution:-
        do_something, 
        do_whatever, 
        assert(solution(X)).
Run Code Online (Sandbox Code Playgroud)

如果未找到解决方案,则第一个规则失败,回溯将尝试第二个规则实现。如果第二个找到解决方案,则第一个规则必须成功,当我再次调用“findsolution/0”时,不再需要回溯,只会查询第一个规则。我的目的是提高效率,防止不必要的查询,因为我知道只有一种解决方案,只是不知道是什么。我很感激。

PS我的程序的上下文在这里不一样,是为了简化。对不起,我的英语不好。

Yas*_*sel 7

如果您想停止搜索,那么您必须做的是使用 cut 谓词避免(控制)回溯,请查看文档
在这种情况下,您需要做的基本上是避免在您的第一个子句中回溯,使用这个 cut (!) 谓词:

findsolution:- solution(X), !.
Run Code Online (Sandbox Code Playgroud)

  • 使用 `once/1` 是更好的风格,因为它的效果更局部:`once(solution(X))`。 (4认同)