根据一系列整数而不是一个整数来划分seq会有什么更惯用的方式?
下面是我的实现:
(defn partition-by-seq
"Return a lazy sequence of lists with a variable number of items each
determined by the n in ncoll. Extra values in coll are dropped."
[ncoll coll]
(let [partition-coll (mapcat #(repeat % %) ncoll)]
(->> coll
(map vector partition-coll)
(partition-by first)
(map (partial map last)))))然后,(partition-by-seq [2 3 6] (range))生成((0 1) (2 3 4) (5 6 7 8 9 10))。
发布于 2013-03-06 03:34:58
Ankur答案的变体,添加了少量的懒惰和when-let,而不是对empty?的显式测试。
(defn partition-by-seq [parts coll]
(lazy-seq
(when-let [s (seq parts)]
(cons
(take (first s) coll)
(partition-by-seq (rest s) (nthrest coll (first s)))))))发布于 2013-03-06 00:38:23
您的实现看起来很好,但可能有一个更简单的解决方案,它使用简单的递归包装在lazy-seq中(事实证明更有效),而不是使用map和现有的partition-by。
(defn partition-by-seq [ncoll coll]
(if (empty? ncoll)
'()
(let [n (first ncoll)]
(cons (take n coll)
(lazy-seq (partition-by-seq (rest ncoll) (drop n coll)))))))发布于 2013-03-06 00:26:34
(first (reduce (fn [[r l] n]
[(conj r (take n l)) (drop n l)])
[[] (range)]
[2 3 6]))
=> [(0 1) (2 3 4) (5 6 7 8 9 10)]https://stackoverflow.com/questions/15228634
复制相似问题