Clojure压缩函数
我需要通过组合给定seq的第一个、第二个等元素来构建seq of seq(vec of vec) 经过快速搜索和查看。我还没有找到一个,我已经完成了自己的写作:Clojure压缩函数,clojure,standard-library,sequences,Clojure,Standard Library,Sequences,我需要通过组合给定seq的第一个、第二个等元素来构建seq of seq(vec of vec) 经过快速搜索和查看。我还没有找到一个,我已经完成了自己的写作: (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 e
(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
docstring:
。。。返回一个惰性序列,该序列由应用f的结果组成
集合首先是每个coll的项,然后对集合应用f
每个coll中的秒项,直到任何一个coll耗尽。
忽略其他Coll中的任何剩余项
Kyle的解决方案是一个很好的解决方案,我看没有理由不使用它,但是如果您想从头开始编写这样一个函数,您可以编写如下内容:
(defn zip
([ret s]
(let [a (map first s)]
(if (every? nil? a)
ret
(recur (conj ret a) (map rest s)))))
([s]
(reverse (zip nil s))))
不是很明显。工作起来很有魅力谢谢此函数通常称为
zip
,而不是unzip
;使用这个非传统的名称可能会使您更难找到现有的实现。是的,您可能是对的,我已经更新了名称。