In this problem, I have three (identically-structured) lists. Two have all numbers and the other is filled with nil. I’m trying to replace the corresponding value in the empty list with the addition of the corresponding values from the two lists. What I have so far utilizes a loop and uses setf to replace the value.
(defun add-two-lists (list1 list2 list3)
(loop for a in list1
for b in list2
for c in list3 do
(setf c (+ a b))))
The problem is that this function is not being destructive. How do I make this function destructive?
Ok, I am aware I could use an apply to do this, but for future or tangent purposes, is there a way to use a loop to do the same thing?
I’ve decided to resort to my penultimate solution; use the list-length to transverse the lists.
(defun add-two-lists (list1 list2 list3)
(loop for x from 0 to (- (list-length list1) 1) do
(setf (nth x list3) (+ (nth x list1) (nth x list2))))
(values list3))
Yet another way to do the same thing without using a loop (though it’s conceptually similar)
EDIT
EDIT 2
But notice the optimized version behavior. Possibly, again, YMMV, but this is what I get on 64-bit Debian with SBCL.