next up previous contents
Next: 5.12.5 Trace Files and Up: 5.12 General Efficiency Hints Previous: 5.12.3 Complex Argument Syntax

5.12.4 Mapping and Iteration

 

One of the traditional Common Lisp programming styles is a highly applicative one, involving the use of mapping functions and many lists to store intermediate results. To compute the sum of the square-roots of a list of numbers, one might say:

(apply #'+ (mapcar #'sqrt list-of-numbers))

This programming style is clear and elegant, but unfortunately results in slow code. There are two reasons why:

An example of an iterative version of the same code:

(do ((num list-of-numbers (cdr num))
     (sum 0 (+ (sqrt (car num)) sum)))
    ((null num) sum))

See sections 5.3.1 and 5.4.1 for a discussion of the interactions of iteration constructs with type inference and variable optimization. Also, section 5.6.4 discusses an applicative style of iteration.



Raymond Toy
Mon Jul 14 09:11:27 EDT 1997