首页 > 解决方案 > 在 Clojure 中将序列懒惰地划分为不同大小的块

问题描述

如何在 Clojure 中将序列懒惰地划分为不同大小的块?有点像(partition n xs),但对于ns. 例如:

(chunker [3 4 5] (range 12))
=> ((0 1 2) (3 4 5 6) (7 8 9 10 11))

标签: clojurepartitioning

解决方案


我需要这个来分块一些输入并且不想使用 Instaparse。这是一个支持循环块大小的惰性解决方案:

(defn chunker
  "Like (partition N input) but for a sequence of Ns."
  [[chunk & chunks] coll]
  (lazy-seq
    (when-let [s (seq coll)]
      (cons (take chunk s)
        (when chunks (chunker chunks (drop chunk s)))))))

用法

(chunker [3 4 5] (range 20))
=> ((0 1 2) (3 4 5 6) (7 8 9 10 11)) ;; note not input not fully consumed.

(chunker (cycle [3 4 5]) (range 20))
=> ((0 1 2) (3 4 5 6) (7 8 9 10 11) (12 13 14) (15 16 17 18) (19))

推荐阅读