Clojure 按整数序列划分
根据一个整数序列而不是仅仅一个整数来划分一个序列的更惯用的方法是什么 以下是我的实现:Clojure 按整数序列划分,clojure,Clojure,根据一个整数序列而不是仅仅一个整数来划分一个序列的更惯用的方法是什么 以下是我的实现: (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 (mapc
(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)))))
然后
(按seq[2 3 6](range))进行分区生成((01)(2 3 4)(5 6 7 8 9 10))
您的实现看起来不错,但是可能有一个更简单的解决方案,它使用简单的递归封装在惰性seq
中(结果证明比使用map和现有的分区更有效)
(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)))))))
Ankur答案的一个变体,在let
而不是显式测试为空时,稍微增加了惰性和
(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)))))))
通过在cons
之外使用lazy seq
,这可能会变得更加懒惰,因此即使是第一个(take n coll)
也不会被急切地评估。我喜欢在let
中使用,因为(cons x nil)只是(x),并且发现它比“if”版本干净得多。为什么使用nthrest
而不是drop
?看起来内部可能是(当让[n(第一部分)](cons(take n coll)(按seq划分)(rest parts)(drop n coll)))
@tobereplacenthrests
只是drop
急切地下降,我认为在这种情况下是合适的。再想一想,我不确定这是否重要。实际上,当let
时,第一个
可以在内移动。
(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)))))))