Reputation:
I need to check if a path is valid, true or false. It's given like this:
?-path(a,b,[(a,c),(c,d),(d,b)]).
true
In the list part, how do I access the a or c in (a,c)? Is it like a string"(a,c)"?
And in general how would one solve this type of path finding? Sample code/pseudo is appreciated. Is there a way to make it interpret the tuples () in the list as predicates?
Upvotes: 1
Views: 511
Reputation: 30023
I'll give you an example from when I was a 2nd year student:
% Representation [[a,b],[b,a],[b,c]]:
%
% a <--> b -->c
%
% Does aexists a path beetween X and Y?
% Example: path(c,b,[[a,b],[b,c],[d,e],[c,d],[b,e],[e,c],[e,f],[a,a]]). No
% path(c,f,[[a,b],[b,c],[d,e],[c,d],[b,e],[e,c],[e,f],[a,a]]). Yes
path(X,Y,G):-pathAux(X,Y,G,[]).
pathAux(X,Y,G,_T):-member([X,Y],G).
pathAux(X,Y,G,T) :-member([X,Z],G),not(member([X,Z],T)),
append([[X,Z]],T,Tt),pathAux(Z,Y,G,Tt).
I used [a,b] instead of (a,b); but It's the same.
Upvotes: 0
Reputation: 10672
You have several questions in there...
Is it like a string"(a,c)"?
What do you mean by "like"? Do they unify? Nope.
?- "(a, c)" = (a, c).
No
In the list part, how do I access the a or c in (a,c)?
?- L = [(a, c) | _], L = [(A, C) | _].
L = [ (a, c)|_G184],
A = a,
C = c
Is there a way to make it interpret the tuples () in the list as predicates?
Maybe using call/N
, but why would you want to do that?
Upvotes: 1
Reputation: 15543
The (a, c) is a compound term, you can access it in a predicate like this:
my_predicate((A, B)) :-
print(A),
print(B).
Upvotes: 0
Reputation: 1994
It's been a while but off the top of my head you'll start with:
path(S, G, [(P, Q) | R]) :- ......
With S meaning start, G meaning goal, P and Q being connected nodes in your graph and R being the rest of your graph.
Upvotes: 0