在Common Lisp中一起压缩列表-"and"问题 [英] Zipping lists together in Common Lisp - Problem with "and"
问题描述
我想做的是创建一个函数zip
(现在要注意,这不是家庭作业),该函数同时遍历多个列表,将一个函数应用于每个元素列表,如下所示:
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))
我想知道如何修复条件语句以与and
一起使用,或达到某种效果.我认为问题出在and
是宏.我还想知道是否已经有内置函数可以做到这一点.
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.
推荐答案
您正在重新实现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)
顺便说一句,您想要在代码中代替all
的函数是and
BTW, the function you want in your code in place of all
is and
这篇关于在Common Lisp中一起压缩列表-"and"问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!