如果我有以下谓词门,声明两个房间之间有一扇门:
door(office, hall). door(kitchen, office). door(hall, "dining room"). door(kitchen, cellar). door("dining room", kitchen).
并且谓词门户宣布门的状态:
doorstate(hall, office, closed). doorstate(hall, "dining room", opened). doorstate("dining room", kitchen, opened). doorstate(kitchen, office, opened). doorstate(kitchen, cellar, opened).
如果两个房间之间的所有门都打开,那么两个房间之间就有一条通道.
如何编写规则来发现两个房间之间是否存在这样的路径?
prolog的可怕恐怖回归太快了.
wayopen(Room1,Room2) :- doorstate(Room1, Room2, opened). wayopen(Room1,Room2) :- doorstate(Room1, RoomX, opened), wayopen(RoomX,Room2).
所以我不只是为你做功课,这里是如何理解它:
两个房间之间的通道是开放的,如果它们是由一个门连接而且门打开了.
如果第一条路通向另一个房间的门,并且从另一个房间到第二个房间有一条路,那么两个房间之间的路是开放的.
请注意,这些规则只能在一个方向上通过门.你的功课是让它在两个方向都有效.
我们在哪里可以从大厅到达?
?- wayopen(hall, X). X = diningroom ; X = kitchen ; X = office ; X = cellar ; false.
以下是您可以从中获取的所有房间:
?- wayopen(Room1,Room2). Room1 = hall, Room2 = diningroom ; Room1 = diningroom, Room2 = kitchen ; Room1 = kitchen, Room2 = office ; Room1 = kitchen, Room2 = cellar ; Room1 = hall, Room2 = kitchen ; Room1 = hall, Room2 = office ; Room1 = hall, Room2 = cellar ; Room1 = diningroom, Room2 = office ; Room1 = diningroom, Room2 = cellar ; false.