Skip to content

Instantly share code, notes, and snippets.

@christianromney
Forked from ddeaguiar/core.clj
Created October 17, 2012 20:35
Show Gist options
  • Save christianromney/3907987 to your computer and use it in GitHub Desktop.
Save christianromney/3907987 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- sum-of
"Sum the collection after applying the given function"
[f coll]
(->> coll
(partition 2)
(map f)
(apply +)))
(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 (sum-of first args))]}
(sum-of #(apply * %) 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)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment