%%% Ugly hack to trace the backtrack tree of a CSP
%%% Copyright Poole, Mackworth, Goebel, 1998
go :-
   set(0,'A',A),set(1,'B',B),
   set(2,'C',C),ch((C \== A,B>C)),
   set(3,'D',D),ch((C\==D,B>D)),
   set(4,'E',E),ch((0 is (10+E-A) mod 2,C>E,D>E)),
   writeln(['success']),
   fail.

% Possible values
val(1).
val(2).
val(3).
val(4).

% ch(C) checks whether constraint C is satisfied.
ch(C) :-
    C,!.
ch(C) :- writeln( ['failure']),
	fail.

% set(Num,Name,V) sets variable Name to have value V where Num is the
%   number of the variable to be assigned (affects the padding).
set(Num,Name,V) :-
   val(V),
   write_set(Num,Name,V).

write_set(_,Name,1) :- !,
   writel([Name,'=',1,' ']).
write_set(Num,Name,V) :-
   write_times(Num,'    '),
   writel([Name,'=',V,' ']).

write_times(0,_) :- !.
write_times(N,S) :-
	write(S),
	N1 is N-1,
	write_times(N1,S).

writel([]).
writel([H|T]) :-
	write(H),
	writel(T).

writeln(L) :- writel(L),nl.
