lambda fairy

Splitting a list into chunks with unfoldr

I’m quite fond of the unfoldr function in Haskell. It doesn’t seem well known, which is a shame because I’ve often found it useful.

One of these uses is in splitting a list into chunks of a specified length. Here are some examples of what I’m going for:

>>> chunks 1 ['a'..'l']

>>> chunks 2 ['a'..'l']

>>> chunks 3 ['a'..'l']

>>> chunks 4 ['a'..'l']

>>> chunks 5 ['a'..'l']

And here’s the definition:

chunks :: Int -> [a] -> [[a]]
chunks = unfoldr $ \xs ->
    case xs of
        -- If there are no elements left, stop iteration
        [] -> Nothing
        -- Otherwise, split off n elements and yield them
        _ -> Just $ splitAt n xs