Processing a list of 1..n elements without explicit recursion

I often find myself using a template where I convert a list with a function that consumes 1..n elements from a list and produces some result from them. For instance.

process :: [a] -> [b]
process [] = []
process xs = first : rest
    where (first, xs') = consume xs
          rest         = process xs'

If the function consumeconsumes a variable number of elements from the list and returns the result and other elements of the list. Can I use some standard higher order function here instead of explicit recursion?

+3
source share
2 answers

The function you need is similar to unfoldr. If you bring consumein the following form:

consume' :: [a] -> Maybe (b,[a])

consume' Nothing Just ... . , :

wrap :: ([a] -> (b,[a])) -> [a] -> Maybe (b,[a])
wrap f [] = Nothing
wrap f xs = Just $ f xs

consume unfoldr consume :: [a] -> (b,[a]) :

unfoldr (wrap consume)
+4

unfoldr consume, , , . Data.List. .

+3

All Articles