Skip to content

Commit f286187

Browse files
Convert a Maybe returning function to Unfold
1 parent d1b75d4 commit f286187

1 file changed

Lines changed: 21 additions & 0 deletions

File tree

  • core/src/Streamly/Internal/Data/Unfold

‎core/src/Streamly/Internal/Data/Unfold/Type.hs‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ module Streamly.Internal.Data.Unfold.Type
5454
, unfoldr
5555
, functionM
5656
, function
57+
, functionMaybeM
5758
, identity
5859

5960
-- * From Values
@@ -886,6 +887,26 @@ functionM f = Unfold step inject
886887
function :: Applicative m => (a -> b) -> Unfold m a b
887888
function f = functionM $ pure Prelude.. f
888889

890+
-- | Lift a monadic Maybe returning function into an unfold. The unfold
891+
-- generates a singleton stream.
892+
--
893+
{-# INLINE functionMaybeM #-}
894+
functionMaybeM :: Monad m => (a -> m (Maybe b)) -> Unfold m a b
895+
functionMaybeM f = Unfold step inject
896+
897+
where
898+
899+
inject a = return (Just a)
900+
901+
{-# INLINE_LATE step #-}
902+
step (Just a) = do
903+
result <- f a
904+
case result of
905+
Just b -> pure $ Yield b Nothing
906+
Nothing -> pure Stop
907+
908+
step Nothing = pure Stop
909+
889910
-- | Identity unfold. The unfold generates a singleton stream having the input
890911
-- as the only element.
891912
--

0 commit comments

Comments
 (0)