Skip to content

Instantly share code, notes, and snippets.

@christianromney
Created October 16, 2012 21:35
Show Gist options
  • Save christianromney/3902193 to your computer and use it in GitHub Desktop.
Save christianromney/3902193 to your computer and use it in GitHub Desktop.
Simple functions to calculate weighted averages in Clojure
(ns rubric.core)
(defn average
"Averages a set of scores"
[& scores]
(/ (apply + scores) (count scores)))
(defn weighted-average
"Calculates a total score from individual weighted results.
Expects pairs of <weight>, <score> whose weights add to 1.0."
[& args]
{:pre [(-> args count even?)
(= 1N (apply + (map first (partition 2 args))))]}
(apply + (map #(apply * %)
(partition 2 args))))
(defn- main
"A quick test of the weighted-average calculation"
[& args]
(println (weighted-average 4/10 (average 96 93.7 97.2 96.4 94.8)
3/10 50
2/10 80
1/10 75)))
@christianromney
Copy link
Author

I think a macro is the only way to avoid calling (partition 2 args) twice.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment