我需要通过组合给定 seq 的第一个、第二个等元素来构建 seq of seq(vec of vec)。
快速搜索并查看 the cheat sheet 后。我还没有找到,所以我自己写了一个:
(defn zip
"From the sequence of sequences return a another sequence of sequenses
where first result sequense consist of first elements of input sequences
second element consist of second elements of input sequenses etc.
Example:
[[:a 0 \\a] [:b 1 \\b] [:c 2 \\c]] => ([:a :b :c] [0 1 2] [\\a \\b \\c])"
[coll]
(let [num-elems (count (first coll))
inits (for [_ (range num-elems)] [])]
(reduce (fn [cols elems] (map-indexed
(fn [idx coll] (conj coll (elems idx))) cols))
inits coll)))
我有兴趣是否有一个标准方法?
最佳答案
(apply map vector [[:a 0 \a] [:b 1 \b] [:c 2 \c]])
;; ([:a :b :c] [0 1 2] [\a \b \c])
您可以使用 map
的变量 arity 来完成此操作。
来自map
文档字符串:
... Returns a lazy sequence consisting of the result of applying f to the set of first items of each coll, followed by applying f to the set of second items in each coll, until any one of the colls is exhausted. Any remaining items in other colls are ignored....
关于Clojure zip 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25854440/