在 Prolog 中获取谓词的所有解决方案 [英] Getting all the solutions to a predicate in Prolog
本文介绍了在 Prolog 中获取谓词的所有解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在 Prolog 中编写文本冒险游戏,并且正在打印房间出口.我有这样的代码:
I'm writing a text adventure game in Prolog, and I am printing out room exits. I have code that does:
exits_from(Room) :-
connected(Room, X),
write(X), write(' ').
connected/2 在哪里:
where connected/2 is:
connected(X, Y) :- path(X, Y).
connected(X, Y) :- path(Y, X).
路径是:
path(room, hallway).
path(hallway, foyer).
等等.
当我打印房间的出口时,它得到第一个,然后需要一个 ';'说我想要另一个解决方案.无论如何要强制谓词完全计算结果,以便玩家不必继续要求更多退出?
When I am printing the exits for a room though, it gets the first, then wants a ';' to say that I want another solution. Is there anyway to force a predicate to compute the result entirely, so that the player wouldn't have to keep asking for more exits?
推荐答案
一种方法是做类似的事情
one way is to do something like
print_all_solutions :-
solution(Sol),
write(Sol),
fail. % this causes backtracking
print_all_solutions. % succed
另一种是使用特殊谓词forall,如下所示:
another is to use special predicate forall, like follows:
forall(solution(Sol), write(Sol))
这篇关于在 Prolog 中获取谓词的所有解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文