maa*_*zza 2 iteration clojure take
嗨,我是 clojure 新手,
我正在尝试创建一个函数,该函数将集合拆分为大小不断增加的块
(apply #(#(take %) (range 1 n)) col)
Run Code Online (Sandbox Code Playgroud)
其中 n 是块的数量
预期输出示例:n = 4 且 col =(范围 1 4)
(1) (2 3) (4)
Run Code Online (Sandbox Code Playgroud)
n = 7 和 col =(范围 1 7)
(1) (2 3) (4 5 6) (7)
Run Code Online (Sandbox Code Playgroud)
你可以使用这样的东西:
(defn partition-inc
"Partition xs at increasing steps of n"
[n xs]
(lazy-seq
(when (seq xs)
(cons (take n xs)
(partition-inc (inc n) (drop n xs))))))
; (println (take 5 (partition-inc 1 (range))))
; ? ((0) (1 2) (3 4 5) (6 7 8 9) (10 11 12 13 14))
Run Code Online (Sandbox Code Playgroud)
或者如果你想有更多的影响,你也可以提供一个大小的序列(行为与上面相同,如果传递(iterate inc 1)给sizes:
(defn partition-sizes
"Partition xs into chunks given by sizes"
[sizes xs]
(lazy-seq
(when (and (seq sizes) (seq xs))
(let [n (first sizes)]
(cons (take n xs) (partition-sizes (rest sizes) (drop n xs)))))))
; (println (take 5 (partition-sizes (range 1 10 2) (range))))
; ? ((0) (1 2 3) (4 5 6 7 8) (9 10 11 12 13 14 15) (16 17 18 19 20 21 22 23 24))
Run Code Online (Sandbox Code Playgroud)