Average using reduce


Originally published at: https://purelyfunctional.tv/reduce-mini/average-using-reduce/
Like we said before, reduce is kind of a universal recursion over lists. We can implement a function to calculate the average using reduce.


In ‘average using reduce,’ why not use a Ratio type to represent the average instead of [int int]? You’d still have to implement that plus function, though you might choose another name. This does work:

user=> (.numerator (/ 1 3))
user=> (.denominator (/ 1 3))

The resulting code might not be quite as pretty but it would plug into the preexisting tools of Clojure better… I think. Any reason why not do it that way?


Hi John,

Great question.

Ratio does indeed represent a ratio. But have you tried writing the code? It would be a good exercise.

Remember, you’re going to need to construct the ratio 0/0 (the initial value).

Give it a shot!

Rock on!


I was wrong. The problem is, you can’t go to the least common denominator. So if your running average is represented by 10/5, a ratio would represent that as 2/1. Then if you wanted to average in a sixth quantity, its numerator would be added to 2, not 10, and your count would be back to 2 instead of updating to 6.

Also, ratios only work with ints. You couldn’t use them to average floats. Well, you could try converting back to a ratio but then you’d have unpredictable numerators/denominators again.


Awesome, @jstoner.

Those are the same things I found.