title: Prolog - Operation inside findall
body: <p>Using a <em>findall</em> in Prolog how can I perform operations inside the goal without affecting backtracking?</p>
  
  <p>The following example explains what I'm trying to achieve:</p>
  
  <pre><code>value('M1', 11, 3).
  value('M2', 11, 3).
  
  connection('M1',1, 'A', 'B').
  connection('M1',1, 'B', 'C').
  connection('M1',2, 'C', 'D').
  connection('M1',2, 'D', 'E').
  connection('M2',1, 'D', 'F').
  
  run :- bbR('C',[(0,'X',['A'])],_,_).
  
  run2 :- bbR2('C',[(0,['A'])],_,_).
  
  bbR(Destination,[(Cost,_,[Destination|T])|_],Result,Cost):-
     reverse([Destination|T],Result).
  bbR(Destination,[(Cost,M_1,[H|T])|Rest],Result,CostSol):-
     write('----'), nl,
     findall( (C, M, [X,H|T]),
              (  Destination\==H,
                 connection(M, CX, H, X),
                 not(member(X,[H|T])),
                 sumValue(M, M_1, F),
                 C is CX+Cost+F,
                 debug_t(H, X, C, F, M)
              ),
              New),
     append(New,Rest,All),
     sort(All,LS),
     bbR(Destination,LS,Result,CostSol).
  
  sumValue(M, M_1, F):-M_1\==M,value(M, 11, F);F is 0.
  
  debug_t(H, X, C, F, M):-
     write('&lt;'),write(H),
     write('&gt; to &lt;'),write(X),
     write('&gt; @ '), write(M),
     write('&gt; total='),write(C),
     write(' e freq='), write(F),
     nl.
  
  bbR2(Destino,[(Cost,[Destino|T])|_],Result,Cost):-
     reverse([Destino|T],Result).
  bbR2(Destino,[(Cost,[H|T])|Rest],Result,CostSol):-
     write('----'), nl,
     findall((C,[X,H|T]),
             (  Destino\==H,
                connection(M, CX, H, X),
                \+ member(X,[H|T]),
                C is CX+Cost,
                debug_t(H, X, C, 0, M)
             ),
             New),
     append(New,Rest,All),
     sort(All,LS),
     bbR2(Destino,LS,Result,CostSol).
  </code></pre>
  
  <p>The problem here is, when I run "run.", it prints:</p>
  
  <pre><code>    &lt;A&gt; to &lt;B&gt; @ M1&gt; total=4 e freq=3
      &lt;A&gt; to &lt;B&gt; @ M1&gt; total=1 e freq=0
  </code></pre>
  
  <p>Whereas if I run "run2." (which is the same code without the call to <em>sumValue</em> and the "+ F") it only prints</p>
  
  <pre><code>    &lt;A&gt; to &lt;B&gt; @ M1&gt; total=1 e freq=0
  </code></pre>
  
  <p>From my debugging it seems the problem is when <em>findall</em> finishes the first goal and backtracks, the <em>sumValue</em> affects it's behavior. </p>
  
  <p>So my main question is <strong>How to sum values (from another predicate) to the variable "C" under certain conditions (in this case, when "M_1" is different to "M") without affecting the <em>findall</em> backtracking</strong>.</p>
  
  <p>I have been trying all day to find a way around this, I already tried using "!" but to no avail.</p>