Prolog Connected Edge Count

I want to make a predicate that checks if a node can reach another node in a graph in the prolog. ect Connected(1,X,[[1,3],[3,4],[2,5]])The first argument is node. I want to run the second, this is the node I want to reach, and the third is a list of edges. So far I have managed to do this, but I get an infinite loop when I try to get all the nodes that I get using findall / 3.

Is there a way to stop an infinite loop, or should I solve the problem from the start?

Here is my code:

 match([X,Y],List):- member([X,Y], List).
 match([X,Y],List):- member([Y,X], List).


go(X,Y,List):-match([X,Y],List).
go(X,Y,List):-match([X,Z],List),go(Z,Y,List).

goes(X,List,List2):-findall(Y,go(X,Y,List),List2).

I am new to Prolog and I cannot understand what I am doing wrong.

+3
source share
2 answers

possible amendment to your code

match([X,Y], List, Rest):- select([X,Y], List, Rest).
match([X,Y], List, Rest):- select([Y,X], List, Rest).

go(X,Y,List) :- match([X,Y],List,_).
go(X,Y,List) :- match([X,Z],List,Rest), go(Z,Y,Rest).

goes(X,List,List2) :- findall(Y, go(X,Y,List), List2).

now matches the "consumes" edge, and then avoids an infinite loop

+4

, ?- gtrace, goes(1,[[1,3],[3,4],[2,5]], X)..

go :- go , .

Traversed, ( ), . , . , , - .

!. .

+1

All Articles