prologriver-crossing-puzzle

Issues with Prolog's write function


The code below should output:

A solution is: 
The farmer takes the Goat from west of the river to east 
The farmer crosses the river from east to west 
The farmer takes the cabbage from west of the river to east 
The farmer takes the Goat from east of the river to west 
The farmer takes the Wolf from west of the river to east 
The farmer crosses the river from east to west 
The farmer takes the Goat from west of the river to east 
No

But I am getting the following error and I can't seem to be able to fix it. If someone can lead me in the right direction, I would really appreciate it.

?- solve.
A solution is:
ERROR: write_move/2: Undefined procedure: write/4
ERROR:   However, there are definitions for:
ERROR:         write/1
ERROR:         writeq/1
ERROR:         write/2
ERROR:         writeq/2
   Exception: (10) write('The farmer takes the Goat from ', west, ' of the river to ', east) ? 

Code: (Partial)

write_move(state(X,W,G,C),state(Y,W,G,C)):- !,

write('The farmer crosses the river from ',X,' to ',Y), nl.

write_move(state(X,X,G,C),state(Y,Y,G,C)):- !,

write('The farmer takes the Wolf from ',X,' of the river to ',Y), nl.

write_move(state(X,W,X,C),state(Y,W,Y,C)):- !,

write('The farmer takes the Goat from ',X,' of the river to ',Y),nl.

write_move(state(X,W,G,X),state(Y,W,G,Y)):- !,

write('The farmer takes the cabbage from ',X,' of the river to ',Y),nl.

If anyone is interested, the prompt for this code is:

Description: A farmer with his goat, wolf and cabbage come to a river that they wish to cross. There is a boat, but it only has room for two, and the farmer is the only one that can row. If the goat and cabbage get in the boat at the same time, the cabbage gets eaten. Similarly, if the wolf and goat are together without the farmer, the goat is eaten. Devise a series of crossings of the river so that all concerned make it across safely.


Solution

  • write/1 only accepts one argument. Undefined procedure write/4 means that there isn't a write/4 defined (write that accepts 4 arguments). The error message indicates that write/1 exists.

    As an alternative to:

    write('The farmer takes the Wolf from ',X,' of the river to ',Y), nl.
    

    You can do one of the following:

    write('The farmer takes the Wolf from '),
    write(X),
    write(' of the river to '),
    write(Y), nl.
    

    Or...

    format('The farmer takes the Wolf from ~w to ~w~n', [X, Y]).
    

    Or (in SWI Prolog)...

    writef('The farmer crosses the river from %w to %w\n', [X, Y]).
    

    And there are probably a couple of other ways... :)