No avg(X) for aggregate_all?

What would the best way to translate the SQL query

select avg(GPA)
from Student;

into Prolog?

I’ve come up with two ways

findall(_GPA, student(_, _, _GPA, _), _GPAs),
sum_list(_GPAs, _T),
length(_GPAs, _L),
Average is _T/_L.

aggregate_all(sum(_GPA), student(_, _, _GPA, _), _T),
aggregate_all(count, student(_, _, _GPA, _), _L),
Average is _T/_L.

It seems weird to me that there’s no

aggregate_all(avg(_GPA), student(_, _, _GPA, _), Average).

So I’m not sure if there is something like that, and I can’t find it in the documentation.

As mentioned previously, I’ve been working through Stanford’s database MooC, doing the problems in both Prolog and Datalog (and finding it very educational, my notes are at SWISH -- SWI-Prolog for SHaring).

1 Like