foldl icon indicating copy to clipboard operation
foldl copied to clipboard

Added premapMaybe(M)

Open YPares opened this issue 8 years ago • 2 comments

While I was at it :) Derived from mapMaybe (in base, Data.Maybe). It can be useful for the same reasons than prefilter.

YPares avatar Nov 06 '17 17:11 YPares

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)

Gabriella439 avatar Nov 06 '17 17:11 Gabriella439

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

Profpatsch avatar Aug 04 '22 12:08 Profpatsch