on master help sign in
Add headElse
41e9492Harendra Kumar
src/Streamly/Internal/Prelude.hs+10
@@ -104,6 +104,7 @@ module Streamly.Internal.Prelude
104 -- -- | Folds that extract selected elements of a stream or their properties.
104 -- -- | Folds that extract selected elements of a stream or their properties.
105 , (!!)
105 , (!!)
106 , head
106 , head
107+ , headElse
107 , findM
108 , findM
108 , find
109 , find
109 , lookup
110 , lookup
@@ -1115,6 +1116,15 @@ null = S.null . toStreamS
1115head :: Monad m => SerialT m a -> m (Maybe a)
1116head :: Monad m => SerialT m a -> m (Maybe a)
1116head = S.head . toStreamS
1117head = S.head . toStreamS
1117
1118
1119+-- | Extract the first element of the stream, if any, otherwise use the
1120+-- supplied default value. It can help avoid one branch in high performance
1121+-- code.
1122+--
1123+-- /Internal/
1124+{-# INLINE headElse #-}
1125+headElse :: Monad m => a -> SerialT m a -> m a
1126+headElse x = D.headElse x . toStreamD
1127+
1118-- |
1128-- |
1119-- > tail = fmap (fmap snd) . uncons
1129-- > tail = fmap (fmap snd) . uncons
1120--
1130--
src/Streamly/Streams/StreamD.hs+5
@@ -122,6 +122,7 @@ module Streamly.Streams.StreamD
122 , drain
122 , drain
123 , null
123 , null
124 , head
124 , head
125+ , headElse
125 , tail
126 , tail
126 , last
127 , last
127 , elem
128 , elem
@@ -896,6 +897,10 @@ null m = foldrM (\_ _ -> return False) (return True) m
896head :: Monad m => Stream m a -> m (Maybe a)
897head :: Monad m => Stream m a -> m (Maybe a)
897head m = foldrM (\x _ -> return (Just x)) (return Nothing) m
898head m = foldrM (\x _ -> return (Just x)) (return Nothing) m
898
899
900+{-# INLINE_NORMAL headElse #-}
901+headElse :: Monad m => a -> Stream m a -> m a
902+headElse a m = foldrM (\x _ -> return x) (return a) m
903+
899-- Does not fuse, has the same performance as the StreamK version.
904-- Does not fuse, has the same performance as the StreamK version.
900{-# INLINE_NORMAL tail #-}
905{-# INLINE_NORMAL tail #-}
901tail :: Monad m => Stream m a -> m (Maybe (Stream m a))
906tail :: Monad m => Stream m a -> m (Maybe (Stream m a))