How to Average in Prolog (2017)
Published on: 2025-07-25 03:54:08
If I had to average a list of numbers, I would probably do it like this:
averagelist(List, Avg) :- length(List, N), sumlist(List, Sum), Avg is Sum / N.
This resembles the actual mathematical definition. Then you could just make a list of numbers and average that. @lurker is right, this is a terrible way to go, but it would work:
average(N, Avg) :- findall(I, between(1, N, I), Is), averagelist(Is, Avg).
This is building up abstraction. But of course, this is for a class and the important thing is to not use Prolog or learn declarative programming or solve actual problems but rather to perform meaningless inductive calisthenics to prove you understand recursion. So a “better” (i.e. worse but likelier to be accepted by a clueless professor) solution is to take the procedural code:
average(list) ::= sum := 0 count := 0 repeat with i ∈ list sum := sum + i count := count + 1 return sum / count
and convert it into equivalent Prolog code:
average(List, Result) :- average(List, 0, 0, Res
... Read full article.