9

What would be a more idiomatic way to partition a seq based on a seq of integers instead of just one integer?

Here's my implementation:

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

Then (partition-by-seq [2 3 6] (range)) yields ((0 1) (2 3 4) (5 6 7 8 9 10)).

4

3 回答 3

4

Your implementation looks fine, but there could be a more simple solution which uses simple recursion wrapped in lazy-seq(and turns out to be more efficient) than using map and existing partition-by as in your case.

(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-05T16:38:23.157 回答
3

A variation on Ankur's answer, with a minor addition of laziness and when-let instead of an explicit test for 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-05T19:34:58.167 回答
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)]
于 2013-03-05T16:26:33.787 回答