Subject: [SWIPL] Backtracking

From: Cortelli Paolo <[email-masked]>
Date: Wed, 20 Dec 2000 11:17:40 +0100

Hi,
   I', trying to create a list with numbers whose sum equals an imposed
limit. All is ok, but I wanted to stop going on when there are no possible
solutions. Of course it a job for the cut, but I can't find the right place
to put it. Can someone help me? 

   Here is the source.

go(Limit,List) :- 
  put_in_list(Limit,[],Num_list),!,
  make_numbers(Limit,0,Num_list,List).

% create a list with the numbers
% ------------------------------
  put_in_list(0,L,L) .
  put_in_list(Limit,L,Num_list) :- 
     Limit1 is Limit - 1,
     Lx = [Limit|L],
     put_in_list(Limit1,Lx,Num_list).

% make a list with all numbers to sum up to Limit
% -----------------------------------------------
  make_numbers(Limit,Limit,_,[]).
  make_numbers(Limit,Sum,Num_list,[T|C]):- 
   select(T,Num_list,Rest),
   plus(T,Sum,S1), 
   S1 =< Limit,	
   make_numbers(Limit,S1,Rest,C).

If S1 =< Limit, then all the list is scanned before before backtracking to
the previous recorsive level.

Thanks for your help.                 Paolo Cortelli