Generally in procedural/imperative languages, it's best practice to place variable declarations as close to usage as possible.
This seems a little hazy in lisp, considering more code is used if there are separate lets
.
Given an example function using two lets
:
(defun draw-box (new-image corners)
(let ((h-len (- (alast (alast corners))
(alast (car corners))))
(h-offset (alast (car corners))))
(dotimes (i h-len)
(setf (aref new-image (car (car corners)) (+ i h-offset) 0) 0)
(setf (aref new-image (car (car corners)) (+ i h-offset) 1) 255)
(setf (aref new-image (car (car corners)) (+ i h-offset) 2) 0)
(setf (aref new-image (car (alast corners)) (+ i h-offset) 0) 0)
(setf (aref new-image (car (alast corners)) (+ i h-offset) 1) 255)
(setf (aref new-image (car (alast corners)) (+ i h-offset) 2) 0)))
(let ((v-len (- (car (alast corners))
(car (car corners))))
(v-offset (car (car corners))))
(dotimes (i v-len)
(setf (aref new-image (+ i v-offset) (alast (car corners)) 0) 0)
(setf (aref new-image (+ i v-offset) (alast (car corners)) 1) 255)
(setf (aref new-image (+ i v-offset) (alast (car corners)) 2) 0)
(setf (aref new-image (+ i v-offset) (alast (alast corners)) 0) 0)
(setf (aref new-image (+ i v-offset) (alast (alast corners)) 1) 255)
(setf (aref new-image (+ i v-offset) (alast (alast corners)) 2) 0))))
Where I'm not going to use v-len
and v-offset
until halfway down the function, I'm hesitant to declare it at the top of the function just to use only a single let
.
What is generally regarded as best practice when declaring variables in longer functions where one might only use a variable later on in the function?
C
has the same rule, unless this has been changed in recent revisions of the language. I think the rationale behind this approach is that a block should never be too long anyway.