Swi prolog finding all the neighbours of a nod in a directed graph -
i have directed graph represented this:
arc(1, 2). arc(1, 4). arc(1, 5). arc(3, 2). arc(3, 7). arc(4, 3). arc(5, 6). arc(6, 8). arc(7, 6). arc(9, 8).
what need predicate put inside list nodes can go specific node. example node 1 resulted list should l=[2,4,5]
because 1 can go 2,4 , 5. doesn't matter how done, matters result, nodes must in list. have tried in couple of ways failed.
an example of how tried it:
road(x,l,l2):- arc(x,y), not(belong(y,l)), append(l,[y],l2), road(x,l2,_). road(x,l,l).
belong(y,l)
predicate returns true if y
found inside of l
.
, example when run road(1,[],l).
result l=[2]
, normal because predicate not written.
when try make using recursion don't know put right stop recursion, hope understand want say.
, tried way using fail didn't worked neither , don't remember how made it.
hope can come solution fast :), in advance.
your code need fair amount of corrections: here working version.
road(x,l,l2) :- arc(x,y), \+ memberchk(y,l), !, road(x,[y|l],l2). road(_,l,l).
it must called way , 'return' list reversed
?- road(1,[],l). l = [5, 4, 2] .
but it's easier - , efficient - use builtin:
?- findall(y, arc(1,y), l).
Comments
Post a Comment