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

Prolog - Find the first solution and stop searching

我正在学习 Prolog 编程,遇到一个规则问题,它必须搜索解决方案,一旦找到,就必须执行 "nothing"。但它失败了,给了我不止一种解决方案。我试着做这样的事情:

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

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

P.S。我程序的上下文在这里不一样,是为了简化。抱歉我的英语不好。

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

findsolution:- solution(X), !.