Post by Jinsong ZhaoHi there,
In the following code example,
(defun a-test (lst)
(let ((a (elt lst 0))
(b (elt lst 1))
(c (elt lst 2)))
(+ a (- c b))))
How to map local variable a, b, and c to the elements of lst? In my
actual code, the lst have 12 elements, and I have 12 named local
variables that appeared in the body with high frequency.
Best,
Jinsong
It isn't clear to us what behavior you want to have from your mapping.
In the code you show, each of the variables is bound to a particular element
of your input list. So you can use them to reference the values of the list.
But each of the variables is a local variable inside the LET form, so any change
to the variable is just a local effect. It will not change the value in the input
list unless the change you make on the local variable is a mutation of the object
that the variable is bound to.
The code you provided should return the value of (+ A (- C B)). What do you
expect it to do?
Some other comments.
In general ELT is not a great function to use on lists, because it has to walk the
list until it gets to the Nth element. If you want to bind a number of variables to
elements of a list, then DESTRUCTURING-BIND will be more convenient and also
more efficient.
But if you have a fixed size list where the individual elements have some meaningful
names, then perhaps an even better approach would be to use a struct (via DEFSTRUCT)
to provide named accessors to the elements. It would also have the side benefit
of being both more space and time efficient.