clojure - 在 Clojure 中将序列懒惰地划分为不同大小的块
问题描述
如何在 Clojure 中将序列懒惰地划分为不同大小的块?有点像(partition n xs)
,但对于ns
. 例如:
(chunker [3 4 5] (range 12))
=> ((0 1 2) (3 4 5 6) (7 8 9 10 11))
解决方案
我需要这个来分块一些输入并且不想使用 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))
推荐阅读
- laravel - 在 laravel 项目中安装 nextjs
- android - 水平 Recyclerview 中的水平 ImageSlider 不起作用
- acrobat - Acrobat 参考库,适用于部分用户,但并非所有用户
- apache-spark - 在分区内合并 parquet 文件
- javascript - JavaScript 如何监听浏览器返回,或者清除历史堆栈?
- java - 不能应用于给定类型;java 实际参数列表和形式参数列表的长度不同
- angular - AWS Amplify:如何调用您自己的重置密码功能?
- ethereum - React,Hardhat前端智能合约方法调用,怎么做?
- javascript - 使用 XMLHttpRequest 传递数据时获取未定义的数组键
- associative-array - 请使用关联数组和可变数组回答此查询