3.3 Average of solutions
This example is a bit harder. The predicate average/3 is defined to take the template average(+Var, :Goal, -Average) , where Goal binds Var and will unify Average with average of the (integer) results.
PlQuery takes the name of a 
predicate and the goal-argument vector as arguments. From this 
information it deduces the arity and locates the predicate. the 
member-function next_solution() yields
TRUE if there was a solution and FALSE 
otherwise. If the goal yielded a Prolog exception it is mapped into a 
C++ exception.
PREDICATE(average, 3)
{ long sum = 0;
  long n = 0;
  PlQuery q("call", PlTermv(A2));
  while( q.next_solution() )
  { sum += (long)A1;
    n++;
  }
  return A3 = (double)sum/(double)n;
}