由一系列整数划分

ToB*_*ced 9 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)))))
Run Code Online (Sandbox Code Playgroud)

然后(partition-by-seq [2 3 6] (range))收益率((0 1) (2 3 4) (5 6 7 8 9 10)).

Raf*_*ird 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)))))))
Run Code Online (Sandbox Code Playgroud)