The less-familiar parts of Lisp for beginners — row-major-aref

We now come to a fairly useful Lisp feature, but again, one that might not have been covered in a basic introduction to Lisp.  The row-major-aref accessor allows the programmer to reference an element in a multi-dimensional array using only a single index.  For operations that require traversing the entire array, this lets the programmer visit all cells without needing to write nested loops, and even allows the code to operate on arrays of different dimensions.  Here is an example of this in use:
*slime-repl sbcl*

CL-USER> (defun sum-array-elements (array)
           (let ((sum 0.0d0))
             (dotimes (i (array-total-size array))
               (incf sum (row-major-aref array i)))
             sum))
SUM-ARRAY-ELEMENTS
CL-USER> (let ((2d-array (make-array (list 10 10)
                                     :initial-element 2))
               (3d-array (make-array (list 10 10 10)
                                     :initial-element 3)))

           (format t "Sum of elements in 2d-array: ~G~%"
                   (sum-array-elements 2d-array))
           (format t "Sum of elements in 3d-array: ~G~%"
                   (sum-array-elements 3d-array)))
Sum of elements in 2d-array: 200.    
Sum of elements in 3d-array: 3000.    
NIL

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*

反垃圾邮件 / Anti-spam question * Time limit is exhausted. Please reload CAPTCHA.