小编Chr*_*her的帖子

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我的程序的上下文在这里不一样,是为了简化。对不起,我的英语不好。

prolog

6
推荐指数
1
解决办法
9232
查看次数

标签 统计

prolog ×1