Created
October 16, 2012 21:35
-
-
Save christianromney/3902193 to your computer and use it in GitHub Desktop.
Simple functions to calculate weighted averages in Clojure
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think a macro is the only way to avoid calling (partition 2 args) twice.