Need to implement a split with foldl
or foldr
.
For example: split [2, 4, 6, 8, 7]
into ([2, 6, 7], [4, 8])
.
Need to implement a split with foldl
or foldr
.
For example: split [2, 4, 6, 8, 7]
into ([2, 6, 7], [4, 8])
.
This is relatively straight-forward. We know the type of our "seed" for the fold, it must be a pair of lists. We alternate which list of the two lists we're appending to by simply swapping the two lists, and we append to list on the left (which will change between each iteration).
foldr (\x (ys,zs) -> (x:zs, ys)) ([],[]) [2,4,6,8,7] -- ([2,6,7],[4,8])
If we were to use foldl
the lists would come out backwards, so foldr
seems like the logical choice.
Given a predicate p :: a -> Bool
you can split on that using foldr
as follows:
split :: (a -> Bool) -> [a] -> ([a],[a])
split p = foldr (\x (as, bs) -> if p x then (x:as, bs) else (as, x:bs)) ([],[])
For example:
Prelude> split (\x -> x `mod` 4 /= 0) [2,4,6,8,7]
([2,6,7],[4,8])