; ; Compute the mean of a list doing only one pass over the list ; ; for comparison, we first show how to do it with two passes by ; folding over the list once to compute the sum and again ; to compute the length (define (sum lst) (foldl + 0 lst)) (define (len lst) (foldl (lambda (_ n) (+ n 1)) 0 lst)) (define (mean1 lst) (/ (sum lst) (len lst))) ; now we do it using a foldl that computes both the sum and ; the length simultaneously using a dotted pair p =(sum . len) ; in one pass. Then computes mean = (car p) / (cdr p) (define (sum-len lst) (foldl (lambda (e p) (cons (+ e (car p)) (+ 1 (cdr p)))) '(0 . 0) lst)) (define (mean2 lst) (let ((p (sum-len lst))) (/ (car p) (cdr p)))) ; alternatively, you could just use a two-element list ; instead of a dotted pair, which using list and cadr ; instead of cons and cdr (see Chapter 2 in Scheme book ; if you are unclear on the difference (define (sum-len2 lst) (foldl (lambda (e p) (list (+ e (car p)) (+ 1 (cadr p)))) '(0 0) lst)) (define (mean3 lst) (let ((p (sum-len2 lst))) (/ (car p) (cadr p)))) (mean1 '(1 2 3 4 5)) (mean2 '(1 2 3 4 5)) (mean3 '(1 2 3 4 5))