Thursday, July 23, 2009

Stop Iterating Down Lists

Over at Abstract Heresies Joe Marshall has two posts that make the point that we shouldn't write code to iterate down a list. We should, instead, use higher order functions such as map or fold. Thus, if we want to sum the squares of a list of numbers, we shouldn't explicitly iterate down the list like this

(define sum-of-squares
 (lambda (numbers)
   (let sum ((l numbers) (sos 0))
     (if (null? l)
         sos
         (sum (cdr l) (+ sos (* (car l) (car l))))))))

but should write something like

(define sum-squares
 (lambda (numbers)
   (fold (lambda (num sum) (+ sum (* num num)))
         0
         numbers)))

It's a good point and one that we tend to forget no matter how fervently we worship at the Church of SICP.

No comments:

Post a Comment