Now that we can safely calculate the average age of a number of pirates, it might be interesting to take this further and calculate the median and standard deviation of the pirates' ages, in addition to their average age.
We already have a function to calculate the average; so, let's just create the ones to calculate the median and the standard deviation of a list of numbers, as follows:
(defn median [& ns] (let [ns (sort ns) cnt (count ns) mid (bit-shift-right cnt 1)] (if (odd? cnt) (nth ns mid) (/ (+ (nth ns mid) (nth ns (dec mid))) 2)))) (defn std-dev [& samples] (let [n (count samples) mean (/ (reduce + samples) n) intermediate (map #(Math/pow (- %1 mean) 2) samples)] (Math/sqrt (/ (reduce + intermediate) n))))
With these functions in place, we can write the code...