File tree Expand file tree Collapse file tree 2 files changed +35
-1
lines changed
Expand file tree Collapse file tree 2 files changed +35
-1
lines changed Original file line number Diff line number Diff line change 402402# @author https://github.com/SuperFola
403403(let iota (fun (_init _length)
404404 (iterate _init (fun (x) (+ 1 x)) _length)))
405+
406+ # @brief Chunk a list in sub-lists of size n
407+ # @param _L list to chunk
408+ # @param _length size of the chunks
409+ # =begin
410+ # (let indices (list:iota 1 9)) # [1 2 3 4 5 6 7 8 9]
411+ # (print (list:chunkBy indices 3)) # [[1 2 3] [4 5 6] [7 8 9]]
412+ # =end
413+ # @author https://github.com/SuperFola
414+ (let chunkBy (fun (_L _length) {
415+ (assert (> _length 0) "list:chunkBy needs a chunk size of at least 1")
416+ (mut _output [])
417+ (mut _current [])
418+ (let _source_len (len _L))
419+
420+ (mut _i 0)
421+ (while (< _i _source_len) {
422+ (append! _current (@ _L _i))
423+ (if (= (len _current) _length)
424+ {
425+ (append! _output _current)
426+ (set _current []) })
427+ (set _i (+ 1 _i)) })
428+
429+ (if (not (empty? _current))
430+ (append! _output _current))
431+
432+ _output }))
Original file line number Diff line number Diff line change 8181 (test:eq (list:iterate 0 (fun (x) (+ 1 x)) 5) [0 1 2 3 4])
8282 (test:eq (list:iterate 0 (fun (x) (+ 1 x)) 5) (list:iota 0 5))
8383 (test:eq (list:iterate "" (fun (x) (+ x "a")) 5) ["" "a" "aa" "aaa" "aaaa"])
84- (test:eq (list:iterate 0 (fun (x) (+ 1 x)) 1) [0]) })
84+ (test:eq (list:iterate 0 (fun (x) (+ 1 x)) 1) [0])
85+
86+ (test:eq (list:chunkBy [1 2] 1) [[1] [2]])
87+ (test:eq (list:chunkBy [1 2 3] 3) [[1 2 3]])
88+ (test:eq (list:chunkBy [1 2 3 4] 3) [[1 2 3] [4]])
89+ (test:eq (list:chunkBy [1 2 3 4 5] 3) [[1 2 3] [4 5]])
90+ (test:eq (list:chunkBy [1 2 3 4 5 6] 3) [[1 2 3] [4 5 6]]) })
You can’t perform that action at this time.
0 commit comments