title: Prolog - How to get the sum of a list's elements?
body: <p>I'm very new to prolog and I am trying to write a little program that, given a list, returns the sum of the list's elements. Following all the examples I've seen led me to a solution that looks like this:</p>
  
  <pre><code>addup([],0).
  addup([FirstNumber | RestOfList], Total) :-
      addup(RestOfList, TotalOfRest),
      Total is FirstNumber + TotalOfRest.
  </code></pre>
  
  <p>But when I test that solution with these values:</p>
  
  <pre><code>?- addup([1,2,3,4],0).
  </code></pre>
  
  <p>I just get garbage values from it like _34521.</p>
  
  <p>Then I tried a second solution that looks like this:</p>
  
  <pre><code>sum([], 0).
  sum([H|T], N):-
      X is H+N,
      sum(T, X).
  </code></pre>
  
  <p>This one is able to add up the numbers correctly, but it is unable to pass the final value of X, which is the true answer, into N. So for the test case:</p>
  
  <pre><code>?- sum([1,2,3,4], 0).
  </code></pre>
  
  <p>I get an answer of 6, the final value of N, and the second-to-last value of X, instead of 10, the final value of X. Any help and/or explanations of why neither of these solutions work would be greatly appreciated. Thanks.</p>