title: aggregating predicates in SWI-Prolog
body: <p>I need to count all <code>X</code> for which <code>some_predicate(X)</code> holds, and there really a lot of such <code>X</code>.
  What is the best way to do that?</p>
  <p>First clue is to <code>findall</code>, accumulate to a list and return the length of the list.</p>
  <pre><code>countAllStuff( X ) :-
      findall( Y
             , permutation( [1,2,3,4,5,6,7,8,9,10], Y )
             , List
             ),
      length( List, X ).
  </code></pre>
  <p><em>(<code>permutation/2</code> is only a dummy placeholder demonstrating that there are many results and that it's bad way to compute the count)</em></p>
  <p>Obviously, with real data, there will be a stack overflow.</p>
  <pre><code>?- countAllStuff( X ).
  ERROR: Out of global stack
  </code></pre>
  <p>Then, I'm trying to replace <code>findall</code> with <code>setof</code>, to no avail.</p>
  <p>At last, I've found the [<code>aggregate</code>][1] (clickable) family of predicates, and trying to use <code>aggregate/3</code> and <code>aggregate/4</code>:</p>
  <pre><code>?- aggregate(count, permutation([1,2,3,4], X), Y ).
  X = [1, 2, 3, 4],
  Y = 1 .
  
  ?- aggregate(count, [1,2,3,4], permutation([1,2,3,4], X), Y ).
  X = [1, 2, 3, 4],
  Y = 1 ;
  X = [1, 2, 4, 3],
  Y = 1 ;
  </code></pre>
  <p>It's all wrong, I think. I need to get something like this:</p>
  <pre><code>?- aggregate(count, permutation([1,2,3,4], X), Y ).
  Y = 24 .
  </code></pre>
  <ol>
  <li><p>What am I doing wrong?</p>
  </li>
  <li><p>How can I declare a predicate to conpute the right answer?
  [1]: <a href="http://www.swi-prolog.org/pldoc/doc/home/vnc/prolog/lib/swipl/library/aggregate.pl" rel="nofollow noreferrer">http://www.swi-prolog.org/pldoc/doc/home/vnc/prolog/lib/swipl/library/aggregate.pl</a></p>
  </li>
  </ol>