Saturday, May 17, 2014

A few simple Clojure functions - mean and median

This post covers some pretty basic Clojure functions which might help a few beginners. For those who have read Clojure documentation properly, they would have come across this definition -

(defn average [x y] (/ (+ x y) 2))

This function takes in two numbers and returns the average of the two of them. Often you would come across situation where you would need to calculate the average over a collection such as a sequence. For those who are not convinced, do it yourself but a simple reduce will not be of any use.

(reduce average [3 4 5])
OUTPUT = 17/4

Which is clearly the wrong answer. Here is one function that calculates average in a more traditional way and reflects Clojure thinking -

(/ (reduce + [3 4 5] ) (.size [3 4 5] ))

This function as expected yields 4 as output. For those who don't want to bring Java in the mix, you have a simple change to make -

(/ (reduce + '(3 4 5) ) (count '(3 4 5) ))

Calculating median is equally simple. For median we would first need to sort the sequence and then if we have odd number of items, we simply return the mid value else we take the average of two middle values.

(def aVector [91 192 201])

(let [ sorted (sort aVector) countd (count aVector)  midPoint  ( int (/ countd 2))]
  (if (odd? countd)
    (nth sorted midPoint)
    ( / (+ (nth sorted midPoint) (nth sorted  (dec midPoint))) 2)
    )
  )

The answer, as expected, comes to 192. 

No comments:

Post a Comment