:- op(700, xfx, l). :- op(700, xfx, r). From l To :- From to To-_. From r To :- From to _-To. answer(Answer) :- path([], aaa, Path), length(Path, Answer). path(_, zzz, []) :- !. % getting full path instead of just length for debugging path(Directions, From, [Move | Cdr]) :- next_step(Directions, Move, Remain), G =.. [Move, From, To], G, path(Remain, To, Cdr). next_step([Move | Remain], Move, Remain). next_step([], Move, Remain) :- direction(Str), atom_chars(Str, [Move | Remain]).