List Slices
October 27, 2020
During some recent personal programming, I needed a function to slice a list into pieces: Given a list of sub-list lengths, and an input list to be sliced, return a list of sub-lists of the requested lengths. For instance:, slicing the list (1 2 2 3 3 3) into sub-lists of lengths (1 2 3) returns the list of sub-lists ((1) (2 2) (3 3 3)). Extra list elements at the end of the input list are ignored, missing list elements at the end of the input list are returned as null lists.
Your task is to write a program that slices lists into sub-lists according to a specification of sub-list lengths. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
Here is an implementation in standard Scheme with no additional dependencies.
Output:
Here is my take on this using Julia 1.5: https://pastebin.com/MiMuvK3V
Pretty straight-forward, through the types need some attention since there is no null for Integers, so I had to use Reals in the output array. Cheers!
Here are two solutions in Python, the first with explicit calculation of slicing indices, and the second relying on
itertools.accumulate
.Output:
Here’s a couple of Haskell solutions, one using an explicit recursion, the other doing a combined map and fold with mapAccumL:
In common lisp by mapping a recursive function that returns a list of k elements from a list over the list of lengths.
(defun slice-list (seq n)
(labels ((rec (s k)
(if (= k 0)
nil
(cons (car s)
(rec (cdr s) (- k 1))))))
(let ((offset 0))
(map 'list
(lambda (k)
(let ((new-offset offset))
(incf offset k)
(rec (subseq seq new-offset) k)))
n))))
(slice-list '(1 2 2 3 3 3) '(1 2 3))
; ((1) (2 2) (3 3 3))
(slice-list '(1 2 2 3 3 3) '(1 2 5))
;((1) (2 2) (3 3 3 NIL NIL))
(slice-list '(1 2 2 3 3 3) '(1 2 1))
;((1) (2 2) (3))