我想了解在 clojure 中对不同大小的集合进行操作的惯用方式。有没有办法告诉函数“map”用一些默认值填充集合的其余部分?
例如,假设我有 3 个向量:
(def x [1 2 3 4])
(def y [1 2 3 4 5])
(def z [1 2 3 4 5 6 7])
(map + x y z) ; yields (3 6 9 12)
在这种情况下,我如何用零填充 x 和 y 并获得此 yield :
(3 6 9 12 10 6 7)
最佳答案
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 的 API 文档,以及 repeat .
这是您如何将其抽象化的草图,因此您无需知道哪个集合最长。 (在上面的代码片段中,如果你
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 的答案。 .
关于collections - 在 clojure 中使用 'map' 和不同大小的集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18940629/