Lisp Code: Add two list

Can we have a function that can add two list to one, such as (add ‘(1 2 3) ‘(4 5 6)) = (5 7 9)

(defun add-two-list (l r)
; e.g. (1 2 3) (2 3 4)
; returns (3 5 7)
  (setf return-value '())
  (loop for i from 0 to (- (length l) 1)
        do (setf return-value (cons (+ (nth i l) (nth i r)) return-value))
)
 (reverse return-value)
)

If we extend this function to add multiple list, then we need the following:

(defun final-get-sum ( l   n )
; get final average value
; e.g. (final-get-sum '((1 1 1) (1 1 1) (1 1 1)) 3)
; returns (3 3 3)
  (cond ((null (car l)) (get-n-zero  n) )
        (t (add-two-list (car l) (final-get-sum (cdr l) n))
        ))
)
 
(defun add-two-list (l r)
; e.g. (1 2 3) (2 3 4)
; returns (3 5 7)
  (setf return-value '())
  (loop for i from 0 to (- (length l) 1)
        do (setf return-value (cons (+ (nth i l) (nth i r)) return-value))
)
 (reverse return-value)
)
 
 
(defun get-n-zero (n)
; get a list with n zeros
 (cond ((equal n 0) nil)
       (t (cons 0 (get-n-zero (- n 1)))))
)

If we go further, we can calculate the average of a list such as
((1 1 1)
(2 2 2)
(3 3 3))
= (2 2 2)

Code

(defun final-get-average (l n)
; l is the final sum, n is the divider =  (length l).
; e.g. 
  (cond ((null (car l)) nil)
        (t (cons (/ (car l) n) (final-get-average (cdr l) n))))
)

May be setf is not a good usage here. But the code above surely works.

1 thought on “Lisp Code: Add two list”

Leave a Comment