由一系列整数分区

时间:2013-03-05 16:10:16

标签: clojure

基于整数的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))

3 个答案:

答案 0 :(得分:4)

您的实现看起来很好,但是可能有一个更简单的解决方案,它使用简单的递归包装在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)))))))

答案 1 :(得分:3)

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)))))))

答案 2 :(得分:2)

(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)]