rtheunissen
rtheunissen

Reputation: 7435

Why is my list not being populated?

For an assignment we are asked to write a predicate route/3 that succeeds if there is a route from Start to Finish, visiting town in the list Visits.

I've come up with an idea for a solution but for some reason the Visits list is always empty after route terminates and I can't figure out why that is. I'm not looking for a solution to the question, just something to point me in the right direction.

Here is my code so far:

Note that my calls to write are simply for debugging reasons.

road('Wellington', 'Palmerston North', 143).
road('Palmerston North', 'Wanganui', 74).
road('Palmerston North', 'Napier', 178).
road('Palmerston North', 'Taupo', 259).
road('Wanganui', 'Taupo', 231).
road('Wanganui', 'New Plymouth', 163).
road('Wanganui', 'Napier', 252).
road('Napier', 'Taupo', 147).
road('Napier', 'Gisborne', 215).
road('New Plymouth', 'Hamilton', 242).
road('New Plymouth', 'Taupo', 289).
road('Taupo', 'Hamilton', 153).
road('Taupo', 'Rotorua', 82).
road('Taupo', 'Gisborne', 334).
road('Gisborne', 'Rotorua', 291).
road('Rotorua', 'Hamilton', 109).
road('Hamilton', 'Auckland', 126).

route(Start, Start, Visits) :-
    write(Visits), nl.

route(Start, Finish, Visits) :-
    write(Visits),nl,
    road(Finish, From, _),
    route(Start, From, [From | Visits]).

test :-
    Visits = [],
    route('Auckland', 'Wellington', Visits),
    write(Visits).

The output when running test.:

1 ?- test.
[]
[Palmerston North]
[Wanganui,Palmerston North]
[Taupo,Wanganui,Palmerston North]
[Hamilton,Taupo,Wanganui,Palmerston North]
[Auckland,Hamilton,Taupo,Wanganui,Palmerston North]
[]
true .

Upvotes: 1

Views: 164

Answers (1)

CapelliC
CapelliC

Reputation: 60004

Variables in Prolog are unified, not assigned. Surely this argument is part of your course.

Then Visits in test keeps the empty list (the accumulator) you 'assigned' when start. You should add (or better, insert) an argument to route, that holds the built list. Something like

test :-
    route('Auckland', 'Wellington', [], Visits),
    write(Visits).

Upvotes: 2

Related Questions