map
不自己动手,但您可以结合使用concat
和repeat
以获得理想的结果:
(def x [1 2 3 4])
(def y [1 2 3 4 5])
(def z [1 2 3 4 5 6 7])
(map +
(concat x (repeat 0))
(concat y (repeat 0))
z) ; => (3 6 9 12 10 6 7)
以下是concat和repeat的API文档。
这里是一个草图,说明如何将这些内容抽象出来,所以你不需要知道哪些集合是最长的。 (在上面的代码片段中,如果你的concat
的所有集合都是(repeat 0)
,那么你将拥有无限的序列)。
(defn map-longest
[f default & colls]
(lazy-seq
(when (some seq colls)
(cons
(apply f (map #(if (seq %) (first %) default) colls))
(apply map-longest f default (map rest colls))))))
(map-longest +
0
[1 2 3 4]
[1 2 3 4 5]
[1 2 3 4 5 6 7]) ; => (3 6 9 12 10 6 7)
您可以看到一些其他方法作为this previous question on Stack Overflow的答案。
来源
2013-09-22 05:39:27
jbm