问题描述
我在 Prolog 中有一个这样的数据库:
I have a database in Prolog like this:
connection(a,b,bus)
connection(b,c,metro)
connection(b,d,taxi)
connection(d,e,bus)
我想要的是我需要应用的规则,以便我可以提出问题:transport(a,c)",它回答:bus"和metro"
What I want is the rules I need to apply so I can ask the question: "transport(a,c)" and it answers: "bus" and "metro"
是否可以定义 1 条或 2 条规则以便查询transport(a,c)"有效?
Is that possible to define 1 or 2 rules so that the query "transport(a,c)" works ?
您应该看到如下所示的数据库:
you should see the database like:
连接(出发,到达,运输).
所以... connection(D,A,T).
那么规则是:
connection(D,A,T):- traject(D,A,T).
connection(D,A,T):- traject(D,X,T1), traject(X,A,T2).
where...traject(Departure, X, Transport1)
和 traject(X, Arrival, Transport2)
where...traject(Departure, X, Transport1)
and traject(X, Arrival, Transport2)
并且查询应该是这样的:
and the query should be something like:
transport(a,c,T1).
和transport(a,c,T2).
然后答案应该是:
T1 = bus
T2 = metro
推荐答案
我会试试这个:
transport(A, B, [Method]) :- connection(A, B, Method).
transport(A, C, [Method|Others]) :-
connection(A, B, Method),
transport(B, C, Others).
这里的基本情况是您有直接连接.归纳案例是找到一个连接,然后从中间递归.请注意,如果您尝试在正文中使用 transport/3
两次而不是 connection/3
然后是 transport/3
,您将获得无限回归!试试看!
The base case here is that you have a direct connection. The inductive case is to find a connection and then recur from the intermediate. Note that you will get an infinite regress if you try using transport/3
twice in the body instead of connection/3
and then transport/3
! Try it and see!
这似乎适用于我期望的输入:
This seems to work for the inputs I expect:
?- transport(a, c, M).
M = [bus, metro] ;
false.
?- transport(a, d, M).
M = [bus, taxi] ;
false.
?- transport(a, e, M).
M = [bus, taxi, bus] ;
false.
希望这会有所帮助!
这篇关于示例中的序言规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!