John Sall
John Sall

Reputation: 1163

Problem with depth first search output in prolog

I have the following code:

s(a, b).
s(b, c).
goal(c).

solve( N, [N] ) :-
    goal( N).

solve( N, [N1 | Sol] ) :-
    s( N, Nl),
    solve( Nl, Sol).

When I enter the query:

solve(a, P).

It gives me :

P = [_,_,c] ? 

yes

But I want the complete path e.g.

P = [a,b,c] ?

Upvotes: 1

Views: 139

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477318

In your predicate you use two variables that look similar (graphically):

solve( N, [N] ) :-
    goal( N).

solve( N, [N1 | Sol] ) :-
    s( N, Nl),
    solve( Nl, Sol).

Here Nl (with a lowercase L) looks similar to N1 (with a one 1). In fact the Prolog interpreter recognizes that N1 is only used once, and raises a warning:

?- ['file.pl'].
Warning: /tmp/file.pl:8:
        Singleton variables: [N1] 
true.

The N1 variable has nothing to do with the Nl variable defined in the body, and thus remains ununified.

But that being said, if you really want to output here, you should use N in the "path" construction, not N1, since otherwise for solve(a, L), L will start with b, not a, and will mention the last node (here c) twice, so:

solve( N, [N] ) :-
    goal( N).

solve(N, [N | Sol]) :-
    s(N, Nl),
    solve(Nl, Sol).

Upvotes: 1

Related Questions