什么会是一个更基于seq整数而不是一个整数分割seq的惯用方法?由整数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))
。
我喜欢在这里使用'when-let',因为(cons x nil)只是(x),并且发现比“if”版本更清洁。为什么使用'nthrest'而不是'drop'?看起来内部部分可能是'(when-let [n(first parts)](cons(take n coll)(partition-by-seq(rest parts)(drop n coll))))' – ToBeReplaced 2013-03-05 20:02:41
@ToBeReplaced' nthrest'只是急速下降的'drop',我认为在这种情况下是合适的。再次想到,我不确定它是否重要。事实上,'第一个'可以在'when-let'中移动。 – 2013-03-05 20:22:32