Prolog Rules in example

2019-09-05 06:49发布

问题:

I have a database in Prolog like this:

connection(a,b,bus)
connection(b,c,metro)
connection(b,d,taxi)
connection(d,e,bus)

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"

Is that possible to define 1 or 2 rules so that the query "transport(a,c)" works ?

you should see the database like:

connection(Departure,Arrive,Transport). so that... connection(D,A,T).

then the rules are:

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) and traject(X, Arrival, Transport2)

and the query should be something like:

transport(a,c,T1). and transport(a,c,T2).

and then the answer should come:

T1 = bus 
T2 = metro 

回答1:

I would try this:

transport(A, B, [Method]) :- connection(A, B, Method).
transport(A, C, [Method|Others]) :-
    connection(A, B, Method),
    transport(B, C, Others).

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.

Hope this helps!



标签: prolog