I find myself often using a pattern where I transform a list with a function that consumes 1..n elements from the list and produces some result out of those. E.g.
process :: [a] -> [b]
process [] = []
process xs = first : rest
where (first, xs') = consume xs
rest = process xs'
Where the consume function consumes a variable number of items from the list and returns a result and the remaining list items. Can I use some standard higher order function here instead of the explicit recursion?
The function you need is similar to
unfoldr. If you would bring yourconsumeinto the following form:Where
consume'returnsNothingin case of an empty list, orJust ...otherwise. This is a small wrapper, that captures that pattern:Then you can use
consumewithunfoldrwith the original definition ofconsume :: [a] -> (b,[a])like this: