foldl
foldl copied to clipboard
Idea for expanding the set of "pre" utilities
In base we have map and filter, and also mapMaybe which can do both, and concatMap that generalized a little further with the additional ability to increase the number of items.
map :: (a -> b) -> [a] -> [b]
filter :: (a -> Bool ) -> [a] -> [a]
mapMaybe :: (a -> Maybe b) -> [a] -> [b]
concatMap :: (a -> [] b) -> [a] -> [b]
For manipulating fold inputs, we have analogs to map and filter. I think it would be quite handy to also have an analog to mapMaybe and concatMap.
premap :: (a -> b) -> Fold b r -> Fold a r
prefilter :: (a -> Bool ) -> Fold a r -> Fold a r
premapMaybe :: (a -> Maybe b) -> Fold b r -> Fold a r
preconcatMap :: (a -> [] b) -> Fold b r -> Fold a r
An implementation for premapMaybe would be
premapMaybe f (Fold step begin done) = Fold step' begin done
where
step' x a = maybe x (step x) (f a)
For example, a fold that I'm currently writing as
Foldl.Fold (\set a -> maybe id Set.insert (f a) set) Set.empty id
could be then written as
Foldl.premapMaybe f Foldl.set
Sure, I would accept a PR for these.