我正在寻找一种将可变参数函数映射到多个列表的简明方法,但我不想像 MAPCAR 那样将列表作为单独的参数传递,而是想传递一个由任意数量的列表组成的列表,并通过这些列表进行映射包含列表。我事先不知道封闭列表中有多少列表,所以我无法解构它。
我尝试过以各种方式组合 MAPCAR 和 APPLY,但无法弄清楚。我必须放弃使用 MAP 并直接明确地编写迭代吗?
这是一个可以完成我想要的功能的函数:
(defun map-within (fn list-of-lists &optional(maptype #'mapcar))
"Map FN on the lists contained in LIST-OF-LISTS"
(cond ((null list-of-lists) nil)
((null (cdr list-of-lists)) (car list-of-lists))
(t
(funcall maptype fn
(car list-of-lists)
(map-within fn (cdr list-of-lists) maptype)))))
在哪里
(map-within #'+ '((1 2 3) (10 20 30) (100 200 300))) => (111 222 333)
是否有一些神奇的 lambda 应用程序可以用一行来表达它?
最佳答案
你可以像这样使用apply
:
(apply #'mapcar #'+ '((1 2 3) (10 20 30) (100 200 300)))
=> (111 222 333)
关于common-lisp - 如何简洁地映射列表列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9060444/