Clojure zip 函数

标签 clojure standard-library sequences

我需要通过组合给定 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/

相关文章:

clojure - 使用 Datomic 返回 Map 而不是 Vector 时出错

c++ - C++ 中何时需要#include <new> 库?

c - 加法序列算法

python - 如何在Python中找到相同的序列

java - Clojure (Java) 和 Ruby 应用程序进行通信的最快可靠方式

clojure - Sublime Text 和 Clojure : Don't pair single quotes

arrays - 为什么Swift标准库中的reverse()函数会返回ReverseRandomAccessCollection?

用于以通用方式返回序列的 C++ API

javascript - 如何在 Clojurescript 中循环 JavaScript 对象并将每个对象插入数组

c - 在 C 中重定向 posix 文件调用