I wrote a function split-seq-by-n
which accepts a sequence and a number and splits the sequence into subsequences of length n (the last subsequence getting the remaining elements). It works on all subclasses of 'sequence
, among others 'string
, 'cons
, 'vector
etc.
;; Splits sequence into subsequences of length n
(defun split-seq-by-n (seq n)
(labels ((seq-split (seq n &optional acc orig-n)
(cond ((zerop (length seq)) (nreverse acc))
((zerop n) (seq-split seq
orig-n
(cons (subseq seq 0 0) acc)
orig-n))
(t (seq-split (subseq seq 1)
(1- n)
(cons (concatenate (class-of seq)
(if acc (car acc) (subseq seq 0 0))
(list (elt seq 0)))
(cdr acc))
orig-n)))))
(seq-split seq n nil n)))
Any comments, improvements, critiques welcome.