foldl
foldl copied to clipboard
Added premapMaybe(M)
While I was at it :) Derived from mapMaybe (in base, Data.Maybe). It can be useful for the same reasons than prefilter.
My main suggestion here is to refactor this as:
folded :: Foldable f => Fold a b -> Fold (f a) b
folded (Fold step begin done) = Fold (foldl' step) begin done
... and then you don't need premapMaybe because it becomes the composition of premap and folded (where f is instantiated to Maybe)
I just implemented the same, because it’s such a common function when dealing with Foldables
-- | Applies a mapMaybe filter to every input element in the fold.
-- Every element for which `Nothing` is returned is dropped from the input.
premapMaybe :: (b -> Maybe a) -> Fold a r -> Fold b r
premapMaybe f (Fold step begin done) = Fold step' begin done
where
step' x b = case f b of
Nothing -> x
Just a' -> step x a'
Another idea is to also have Fold implement Filterable and maybe Witherable from https://hackage.haskell.org/package/witherable-0.4.2/docs/Witherable.html