on master help sign in
Add headElse
commit41e94929564e69473dccbe82477ba175fd514962 authorHarendra Kumar <harendra.kumar@gmail.com> dateSat 23 Nov 2019, 17:03 (7 years ago) parent35ba2c3
2 files changed+15
src/Streamly/Internal/Prelude.hs+10 src/Streamly/Streams/StreamD.hs+5
src/Streamly/Internal/Prelude.hs+10
@@ -104,6 +104,7 @@ module Streamly.Internal.Prelude
104104 -- -- | Folds that extract selected elements of a stream or their properties.
105105 , (!!)
106106 , head
107+ , headElse
107108 , findM
108109 , find
109110 , lookup
@@ -1115,6 +1116,15 @@ null = S.null . toStreamS
11151116head :: Monad m => SerialT m a -> m (Maybe a)
11161117head = S.head . toStreamS
11171118
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+
11181128-- |
11191129-- > tail = fmap (fmap snd) . uncons
11201130--
src/Streamly/Streams/StreamD.hs+5
@@ -122,6 +122,7 @@ module Streamly.Streams.StreamD
122122 , drain
123123 , null
124124 , head
125+ , headElse
125126 , tail
126127 , last
127128 , elem
@@ -896,6 +897,10 @@ null m = foldrM (\_ _ -> return False) (return True) m
896897head :: Monad m => Stream m a -> m (Maybe a)
897898head m = foldrM (\x _ -> return (Just x)) (return Nothing) m
898899
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+
899904-- Does not fuse, has the same performance as the StreamK version.
900905{-# INLINE_NORMAL tail #-}
901906tail :: Monad m => Stream m a -> m (Maybe (Stream m a))