0

I'm new to Prolog. I'm trying to search simple pathes using prolog, but only base cases(length 1 or 0) were found. What's wrong? Code

I rewrited the recursion part referencing several examples which perform dfs or list manipulation.

Paulo Moura
  • 18,373
  • 3
  • 23
  • 33
  • 3
    Please post your code as text, not an image of text. – Scott Hunter Jul 25 '23 at 12:46
  • Usual reminder: You can step through your program, to see exactly what is happening and where it is going wrong, using e.g. `trace.` - https://www.swi-prolog.org/pldoc/man?section=debugger – brebs Jul 25 '23 at 14:16
  • Put the `arc(Node` line **before** the `not(member(` line, so that `Node` gets instantiated as intended. Also, use different predicate names for the data (i.e. a,b,c,d) vs algorithms, to avoid infinite loops - applies to `simple_path` and `arc`. – brebs Jul 25 '23 at 14:21

1 Answers1

1

Use the following implementation as a starting point: Definition of a path/trail/walk

Just copy the whole "Implementation" section to your program.

Then, the rest is the definition of your graph. You can do it like this:

arc(a,b).
arc(c,d).
arc(b,d).

n(A,B) :-
    (   arc(A,B)
    ;   arc(B,A)
    ).

This is it. You can now try:

?- path(n, Path, a, B).
Path = [a],
B = a ;
Path = [a, b],
B = b ;
Path = [a, b, d],
B = d ;
Path = [a, b, d, c],
B = c ;
false.

?- path(n, Path, A, d).
Path = [d],
A = d ;
Path = [a, b, d],
A = a ;
Path = [c, d],
A = c ;
Path = [b, d],
A = b ;
false.

?- path(n, Path, _, _).
Path = [_] ;
Path = [a, b] ;
Path = [a, b, d] ;
Path = [a, b, d, c] ;
Path = [c, d] ;
Path = [c, d, b] ;
Path = [c, d, b, a] ;
Path = [b, d] ;
Path = [b, d, c] ;
Path = [b, a] ;
Path = [d, c] ;
Path = [d, b] ;
Path = [d, b, a] ;
false.
TA_intern
  • 2,222
  • 4
  • 12