## Computing Weighted Averages

It's easy to compute a weighted average incorrectly if you're not
careful. A weighted average should have the property that if an
assignment has a weight of, say 10% of the final grade, it should have
that weight whether the assignment is graded on a scale of 100 or a
scale of 20.
The following bit of code does the weighted-average algorithm
correctly:

;; weighted-average : ListOf<Number> ListOf<Number>
ListOf<Number> -> Number
;; GIVEN: a list of actual scores, a list of maximum possible
;; scores, and a list of relative weights
;; RETURNS: the weighted average.
;; EXAMPLEs:
;; (weighted-average (list 5 10) (list 10 10) (list 1 1)) = .75
;; (weighted-average (list 5 10) (list 10 10) (list 0 1)) = 1.0
;; strategy: function composition
(define (weighted-average scores maxes weights)
(let ((weighted-sum
(sum
(map
(lambda (score max weight) (* (/ score max) weight))
scores maxes weights)))
(total-weight (sum weights)))
(/ weighted-sum total-weight)))
;; sum : ListOf<Number> -> Number
;; GIVEN a list of numbers,
;; RETURNS: their sum
;; Example:
;; (sum (list 3 4 1)) = 8
;; (sum empty) = 0
;; strategy: higher-order function composition
(define sum
(lambda (l)
(foldr + 0 l)))

Last modified: Mon Jul 29 17:23:40 -0400 2013