在 PyDatalog 中,我定义了以下断言:
#stations
assert_fact('station', 'A' ,'yellow')
assert_fact('station', 'B' ,'yellow')
assert_fact('station', 'C' ,'yellow')
assert_fact('station', 'D' ,'yellow')
#sections
assert_fact('stretch', 'A' ,'B')
assert_fact('stretch', 'B' ,'C')
assert_fact('stretch', 'C', 'D')
而且我想询问数据库是否有办法从 A 到 D。 下面的代码应该可以工作,因为如果有办法,它会回答 set([()]) ,如果没有,它会回答 None 。但它没有给我 Z 的不同评估的结果。我也想知道路线,例如:A B C D
load("""
route(X,Y) <= stretch(X,Y)
route(X,Y) <= stretch(X,Z) & route(Z,Y)
""")
我试过使用未绑定(bind)的值,但它只给了我第一次迭代的结果:
load("""
route(X,Y,P) <= stretch(X,Y) & (P==Y)
route(X,Y,P) <= stretch(X,P) & route(P,Y,Z)
""")
我认为问题在于它在第一次迭代中只需要 P。还是应该使用聚合函数?我不太明白如何使用 concat...
提前致谢。
最佳答案
您需要一个带有变量的谓词,该变量包含两个端点之间的节点。您可以使用以下 route() 定义:
load("""
route(X,P, Y) <= stretch(X,Y) & (P==[])
route(X,P, Y) <= stretch(X,Z) & route(Z,P1,Y) & ~(Z in P1) & (P==[Z]+P1)
""")
print(pyDatalog.ask("route('A', P, 'D')"))
# prints set([(('B', 'C'),)])
自 pyDatalog 0.13 起支持列表。
关于logic-programming - PyDatalog:答案中的值列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19773176/