What I am trying to do is create a function zip
(note now that this is not homework) that iterates through multiple lists simultaneously, applying a function to each list of elements, like so:
(zip f '(1 2 3) '(4 5 6) '(7 8 9)) = (list (f 1 4 7) (f 2 5 8) (f 3 6 9))
(zip f '(1 2 3 4) '(5 6) '(7 8 9)) = (list (f 1 5 7) (f 2 6 8))
Basically, it stops when any开发者_如何转开发 list runs out of elements. Here is my current attempt:
(defun zip (f &rest lists)
(if (apply and lists) ; <- Here is where I think the problem is.
(cons (apply f (mapcar #'car lists)) (zip f &rest (mapcar #'cdr lists)))
nil))
I would like to know how fix the conditional statement to work with and
, or something to that effect. I think the problem arises from and
being a macro. I would also like to know if there is a built-in function for doing this already.
You are re-implementing mapcar
? (mapcar #'list '(1 2 3) '(4 5 6) '(7 8 9))
((1 4 7) (2 5 8) (3 6 9))
? (mapcar #'list '(1 2 3 4) '(5 6) '(7 8 9))
((1 5 7) (2 6 8))
? (mapcar #'+ '(1 2 3) '(4 5 6) '(7 8 9))
(12 15 18)
? (mapcar #'+ '(1 2 3 4) '(5 6) '(7 8 9))
(13 16)
BTW, the function you want in your code in place of all
is and
精彩评论