Code below is answer to an exercise in Paul Graham's ANSI Common Lisp (ex. 4.1). The challenge is to rotate an array by 90 degrees. I found an example solution which I've commented below.
It seems ok'ish and I'm enjoying learning how to use do, but in this particular case it seems actually more verbose than the familir c-style nested for loops to process a 2d array. I'm wondering if the below is good style or if it can be improved upon?
Is the answer going to be the loop macro? I'm avoiding that at the moment while learning, waiting till I have better mastery of the basics. Yet would like to not pick up bad habits. Hence this question about style regarding the below.
(defun quarter-turn (arr)
(let* ((dim (array-dimensions arr)) ; let* sets sequentially, not in parallel.
(row (first dim))
(col (second dim))
(n row) ; initialise n to row, just to organise
new-arr) ; shorthand for (new-arr nil)
(cond ((not (= row col))
(format t "The arg is not a square array.~%"))
(t (setf new-arr (make-array dim :initial-element nil))
(do ((i 0 (+ i 1))) ; Q. surprisingly, lisp's 'do' here looks more
((= i n)) ; verbose than c-style 'for'. Is this good style?
(do ((j 0 (+ j 1)))
((= j n))
(setf (aref new-arr j i) (aref arr (- n i 1) j))))
new-arr))))
Source for the above code: http://www.cs.uml.edu/~lhao/ai/lisp/ansi-common-lisp/solution-ch04.htm