我无法解决 Learn Prolog Now 练习(本页的最后一个)。简而言之:有一堆格式为“byCar (place1, place2)”、“byTrain (place1, place2)”和“byAirplane (place1, place2)”的事实,我必须编写一个 travel/3 谓词(我称之为门票)告诉您从地点 1 到地点 2 需要购买哪些门票。
例如,查询
tickets(valmont, losAngeles, X)
应该返回这样的答案:
X = goByCar(valmont, saarbruecken,
goByTrain(saarbruecken, frankfurt,
goByAirplane(frankfurt, bangkok,
goByAirplane(bangkok, auckland,
goByAirplane(auckland, losAngeles)))))
我目前的解决方案是:
ticketsDir(A, B, goByCar(A, B)) :- byCar(A, B).
ticketsDir(A, B, goByTrain(A, B)) :- byTrain(A, B).
ticketsDir(A, B, goByAirplane(A, B)) :- byAirplane(A, B).
swapGo(goByCar(A, B)) :- goByCar(B, A).
swapGo(goByTrain(A, B)) :- goByTrain(B, A).
swapGo(goByAirplane(A, B)) :- goByAirplane(B, A).
mergeGo(goByCar(A, B), Go2) :- goByCar(A, B, Go2).
mergeGo(goByTrain(A, B), Go2) :- goByTrain(A, B, Go2).
mergeGo(goByAirplane(A, B), Go2) :- goByAirplane(A, B, Go2).
tickets(A, B, Go) :- ticketsDir(A, B, Go).
tickets(A, B, swapGo(Go)) :- ticketsDir(B, A, Go).
tickets(A, B, mergeGo(Go1, Go2)) :- ticketsDir(A, Z, Go1), tickets(Z, B, Go2).
tickets(A, B, mergeGo(Go1, Go2)) :- ticketsDir(Z, A, Go1), tickets(Z, B, Go2).
但是,该查询返回以下结果:
X = mergeGo(goByCar(valmont, saarbruecken),
mergeGo(goByTrain(saarbruecken, frankfurt),
mergeGo(goByAirplane(frankfurt, bangkok),
mergeGo(goByAirplane(bangkok, auckland),
swapGo(goByAirplane(losAngeles, auckland))))))"
现在奇怪的是,查询
swapGo(goByCar(A, B))
返回:
Error: swapGo/1: Undefined procedure: goByCar/2
和查询
mergeGo(goByCar(A, B), go2)
返回:
Error: mergeGo/2: Undefined procedure: goByCar/3
似乎我错误地定义了“swapGo”和“mergeGo”,或者“tickets”。有什么建议可以解决吗?谢谢!