1{-# OPTIONS_GHC -Wno-orphans #-}
6-- Module : Streamly.Internal.Data.Stream.IsStream
7-- Copyright : (c) 2017 Harendra Kumar
10-- Maintainer : streamly@composewell.com
11-- Stability : experimental
14-- This is an Internal module consisting of released, unreleased and
15-- unimplemented APIs. For stable and released APIs please see
16-- "Streamly.Prelude" module. This module provides documentation only for the
17-- unreleased and unimplemented APIs. For documentation on released APIs please
18-- see "Streamly.Prelude" module.
20module Streamly.Internal.Data.Stream.IsStream
29 -- ** Speculative Streams
33 -- ** Asynchronous Streams
48 -- * Stream Type Adapters
87 -- ** Time Enumeration
108 -- ** Cyclic Elements
111 -- ** From Containers
138 -- ** Composable Left Folds
144 -- ** Concurrent Folds
151 -- -- ** To Summary (Full Folds)
159 -- -- ** To Summary (Maybe) (Full Folds)
167 -- -- ** To Containers (Full Folds)
173 -- ** Composable Left Folds
175 , toStream -- XXX rename to write?
176 , toStreamRev -- XXX rename to writeRev?
180 -- -- ** To Elements (Partial Folds)
184 -- -- | Folds that extract selected elements of a stream or their properties.
194 -- -- ** To Boolean (Partial Folds)
203 -- ** Multi-Stream folds
208 -- finding subsequences
214 -- trimming sequences
254 -- ** Scan Using Fold
258 -- XXX Once we have pipes the contravariant transformations can be
259 -- represented by attaching pipes before a transformation.
271 -- ** Concurrent Transformation
283 -- ** Deleting Elements
286 -- , uniqBy -- by predicate e.g. to remove duplicate "/" in a path
287 -- , uniqOn -- to remove duplicate sequences
288 -- , pruneBy -- dropAround + uniqBy - like words
290 -- ** Inserting Elements
299 , intersperseSuffixBySpan
300 -- , intersperseBySpan
301 -- , intersperseByIndices -- using an index function/stream
303 -- time domain intersperse
304 -- , intersperseByTime
305 -- , intersperseByEvent
316 -- , timestampedR -- timer
354 -- -- *** Searching Elements
358 -- -- *** Searching Sequences
359 -- , seqIndices -- search a sequence in the stream
361 -- -- *** Searching Multiple Sequences
362 -- , seqIndicesAny -- search any of the given sequence in the stream
364 -- -- -- ** Searching Streams
365 -- -- | Finding a stream within another stream.
368 -- | Streams can be sliced into segments in space or in time. We use the
369 -- term @chunk@ to refer to a spatial length of the stream (spatial window)
370 -- and the term @session@ to refer to a length in time (time window).
372 -- -- *** Using Element Separators
380 , wordsBy -- stripAndCompactBy
382 -- -- *** Splitting By Sequences
385 -- , splitOnPrefixSeq
387 -- Keeping the delimiters
390 -- , splitByPrefixSeq
393 -- Splitting using multiple sequence separators
395 -- , splitOnAnySuffixSeq
396 -- , splitOnAnyPrefixSeq
398 -- -- *** Splitting By Streams
399 -- -- | Splitting a stream using another stream as separator.
406 -- In imperative terms, grouped folding can be considered as a nested loop
407 -- where we loop over the stream to group elements and then loop over
408 -- individual groups to fold them to a single value that is yielded in the
421 -- * Windowed Classification
423 -- | Split the stream into windows or chunks in space or time. Each window
424 -- can be associated with a key, all events associated with a particular
425 -- key in the window can be folded to a single result. The stream is split
426 -- into windows of specified size, the window can be terminated early if
427 -- the closing flag is specified in the input stream.
429 -- The term "chunk" is used for a space window and the term "session" is
430 -- used for a time window.
432 -- ** Tumbling Windows
433 -- | A new window starts after the previous window is finished.
435 -- , classifyChunksOf
439 -- ** Keep Alive Windows
440 -- | The window size is extended if an event arrives within the specified
441 -- window size. This can represent sessions with idle or inactive timeout.
443 -- , classifyKeepAliveChunks
444 , classifyKeepAliveSessions
447 -- ** Sliding Windows
448 -- | A new window starts after the specified slide from the previous
449 -- window. Therefore windows can overlap.
450 , classifySlidingChunks
451 , classifySlidingSessions
453 -- ** Sliding Window Buffers
454 -- , slidingChunkBuffer
455 -- , slidingSessionBuffer
457 -- * Combining Streams
497 -- ** Flattening a Container of Streams
499 , concatMapFoldableWith
500 , concatForFoldableWith
502 -- ** Flattening a Stream of Streams
511 -- ** Flattening Using Unfolds
513 , concatUnfoldInterleave
514 , concatUnfoldRoundrobin
516 -- ** Flattening a Tree of Streams
519 -- ** Flattening a Graph of Streams
522 -- ** Inserting Streams in Streams
542 -- * Generalize Inner Monad
546 -- * Transform Inner Monad
562 , iterateMapLeftsWith
564 -- * Concurrency Control
594import Control.Concurrent (threadDelay)
595import Control.Exception (Exception, assert)
596import Control.Monad (void)
597import Control.Monad.Catch (MonadCatch, MonadThrow)
598import Control.Monad.IO.Class (MonadIO(..))
599import Control.Monad.Trans.Reader (ReaderT)
600import Control.Monad.Trans.State.Strict (StateT)
601import Control.Monad.Trans.Class (MonadTrans(..))
602import Control.Monad.Trans.Control (MonadBaseControl)
603import Data.Either (isLeft, isRight)
604import Data.Functor.Identity (Identity (..))
605import Data.Kind (Type)
606import Data.Heap (Entry(..))
607import Data.Maybe (isJust, fromJust, isNothing)
608import Data.Void (Void)
609import Foreign.Storable (Storable)
610import Streamly.Internal.BaseCompat (fromLeft, fromRight)
611import Streamly.Internal.Data.Stream.Enumeration
612 (Enumerable(..), enumerate, enumerateTo)
613import Streamly.Internal.Data.Fold.Types (Fold (..), Fold2 (..))
614import Streamly.Internal.Data.Parser (Parser (..))
615import Streamly.Internal.Data.Unfold.Types (Unfold)
616import Streamly.Internal.Data.Array.Storable.Foreign.Types (Array, writeNUnsafe)
617import Streamly.Internal.Data.SVar (MonadAsync, defState, Rate (..))
618import Streamly.Internal.Data.Stream.Ahead (AheadT, Ahead, ahead, aheadly)
619import Streamly.Internal.Data.Stream.Async
620 ( AsyncT, Async, WAsyncT, WAsync, mkAsync, async, asyncly, wAsync
622import Streamly.Internal.Data.Stream.Combinators
623 ( inspectMode, maxBuffer, maxThreads, maxYields, rate, avgRate, minRate
624 , maxRate, constRate)
625import Streamly.Internal.Data.Stream.Parallel
626 ( ParallelT, Parallel, parallel, parallely)
627import Streamly.Internal.Data.Stream.Prelude
628 (fromStreamS, toStreamS, concatFoldableWith, concatMapFoldableWith
629 , concatForFoldableWith)
630import Streamly.Internal.Data.Stream.StreamD (fromStreamD, toStreamD)
631import Streamly.Internal.Data.Stream.StreamK (IsStream((|:), consM), adapt)
632import Streamly.Internal.Data.Stream.Serial
633 ( SerialT, WSerialT, Serial, WSerial, serial, wSerial, serially
635import Streamly.Internal.Data.Stream.Zip
636 ( ZipSerialM, ZipSerial, ZipAsyncM, ZipAsync, zipSerially, zipAsyncly)
637import Streamly.Internal.Data.Pipe.Types (Pipe (..))
638import Streamly.Internal.Data.Time.Units
639 ( AbsTime, MilliSecond64(..), addToAbsTime, toRelTime
640 , toAbsTime, TimeUnit64, RelTime64, addToAbsTime64)
641import Streamly.Internal.Data.IORef.Prim (Prim, IORef)
642import Streamly.Internal.Data.Tuple.Strict (Tuple'(..))
644import qualified Streamly.Internal.Data.Array.Storable.Foreign as A
645import qualified Streamly.Data.Fold as FL
646import qualified Streamly.Internal.Data.Fold.Types as FL
647import qualified Streamly.Internal.Data.Stream.Prelude as P
648import qualified Streamly.Internal.Data.Stream.StreamK as K
649import qualified Streamly.Internal.Data.Stream.StreamD as D
650import qualified Streamly.Internal.Data.Stream.Serial as Serial
651import qualified Streamly.Internal.Data.Stream.Parallel as Par
652import qualified Streamly.Internal.Data.Stream.Zip as Z
653import qualified Streamly.Internal.Data.Parser.ParserK.Types as PRK
654import qualified Streamly.Internal.Data.Parser.ParserD as PRD
655import qualified Data.Heap as H
656import qualified Data.Map.Strict as Map
657import qualified Prelude
658import qualified System.IO as IO
659#ifdef USE_STREAMK_ONLY
660import qualified Streamly.Internal.Data.Stream.StreamK as S
662import qualified Streamly.Internal.Data.Stream.StreamD as S
666 ( filter, drop, dropWhile, take, takeWhile, zipWith, foldr
667 , foldl, map, mapM, mapM_, sequence, all, any, sum, product, elem
668 , notElem, maximum, minimum, head, last, tail, length, null
669 , reverse, iterate, init, and, or, lookup, foldr1, (!!)
670 , scanl, scanl1, replicate, concatMap, span, splitAt, break
671 , repeat, concat, mconcat)
673------------------------------------------------------------------------------
675------------------------------------------------------------------------------
677-- | Decompose a stream into its head and tail. If the stream is empty, returns
678-- 'Nothing'. If the stream is non-empty, returns @Just (a, ma)@, where @a@ is
679-- the head of the stream and @ma@ its tail.
681-- This is a brute force primitive. Avoid using it as long as possible, use it
682-- when no other combinator can do the job. This can be used to do pretty much
683-- anything in an imperative manner, as it just breaks down the stream into
684-- individual elements and we can loop over them as we deem fit. For example,
685-- this can be used to convert a streamly stream into other stream types.
689uncons :: (IsStream t, Monad m) => SerialT m a -> m (Maybe (a, t m a))
690uncons m = K.uncons (K.adapt m)
692------------------------------------------------------------------------------
693-- Generation by Unfolding
694------------------------------------------------------------------------------
701-- Just (a, b) -> a \`cons` unfoldr step b
704-- Build a stream by unfolding a /pure/ step function @step@ starting from a
705-- seed @s@. The step function returns the next element in the stream and the
706-- next seed value. When it is done it returns 'Nothing' and the stream ends.
713-- else Just (b, b + 1)
714-- in toList $ unfoldr f 0
721{-# INLINE_EARLY unfoldr #-}
722unfoldr :: (Monad m, IsStream t) => (b -> Maybe (a, b)) -> b -> t m a
723unfoldr step seed = fromStreamS (S.unfoldr step seed)
724{-# RULES "unfoldr fallback to StreamK" [1]
725 forall a b. S.toStreamK (S.unfoldr a b) = K.unfoldr a b #-}
727-- | Build a stream by unfolding a /monadic/ step function starting from a
728-- seed. The step function returns the next element in the stream and the next
729-- seed value. When it is done it returns 'Nothing' and the stream ends. For
735-- then return Nothing
736-- else print b >> return (Just (b, b + 1))
737-- in drain $ unfoldrM f 0
745-- When run concurrently, the next unfold step can run concurrently with the
746-- processing of the output of the previous step. Note that more than one step
747-- cannot run concurrently as the next step depends on the output of the
751-- (asyncly $ S.unfoldrM (\\n -> liftIO (threadDelay 1000000) >> return (Just (n, n + 1))) 0)
752-- & S.foldlM' (\\_ a -> threadDelay 1000000 >> print a) ()
758{-# INLINE_EARLY unfoldrM #-}
759unfoldrM :: (IsStream t, MonadAsync m) => (b -> m (Maybe (a, b))) -> b -> t m a
762{-# RULES "unfoldrM serial" unfoldrM = unfoldrMSerial #-}
763{-# INLINE_EARLY unfoldrMSerial #-}
764unfoldrMSerial :: MonadAsync m => (b -> m (Maybe (a, b))) -> b -> SerialT m a
765unfoldrMSerial = Serial.unfoldrM
767{-# RULES "unfoldrM wSerial" unfoldrM = unfoldrMWSerial #-}
768{-# INLINE_EARLY unfoldrMWSerial #-}
769unfoldrMWSerial :: MonadAsync m => (b -> m (Maybe (a, b))) -> b -> WSerialT m a
770unfoldrMWSerial = Serial.unfoldrM
772{-# RULES "unfoldrM zipSerial" unfoldrM = unfoldrMZipSerial #-}
773{-# INLINE_EARLY unfoldrMZipSerial #-}
774unfoldrMZipSerial :: MonadAsync m => (b -> m (Maybe (a, b))) -> b -> ZipSerialM m a
775unfoldrMZipSerial = Serial.unfoldrM
777-- | Convert an 'Unfold' into a stream by supplying it an input seed.
779-- >>> unfold (UF.replicateM 10) (putStrLn "hello")
783unfold :: (IsStream t, Monad m) => Unfold m a b -> a -> t m b
784unfold unf x = fromStreamD $ D.unfold unf x
786-- | Convert an 'Unfold' with a closed input end into a stream.
789{-# INLINE unfold0 #-}
790unfold0 :: (IsStream t, Monad m) => Unfold m Void b -> t m b
791unfold0 unf = unfold unf (error "unfold0: unexpected void evaluation")
793------------------------------------------------------------------------------
794-- Specialized Generation
795------------------------------------------------------------------------------
797-- Faster than yieldM because there is no bind.
801-- yield a = a \`cons` nil
804-- Create a singleton stream from a pure value.
806-- The following holds in monadic streams, but not in Zip streams:
810-- yield = yieldM . pure
813-- In Zip applicative streams 'yield' is not the same as 'pure' because in that
814-- case 'pure' is equivalent to 'repeat' instead. 'yield' and 'pure' are
815-- equally efficient, in other cases 'yield' may be slightly more efficient
816-- than the other equivalent definitions.
820yield :: IsStream t => a -> t m a
825-- yieldM m = m \`consM` nil
828-- Create a singleton stream from a monadic action.
831-- > toList $ yieldM getLine
838yieldM :: (Monad m, IsStream t) => m a -> t m a
843-- fromIndices f = let g i = f i \`cons` g (i + 1) in g 0
846-- Generate an infinite stream, whose values are the output of a function @f@
847-- applied on the corresponding index. Index starts at 0.
850-- > S.toList $ S.take 5 $ S.fromIndices id
855{-# INLINE fromIndices #-}
856fromIndices :: (IsStream t, Monad m) => (Int -> a) -> t m a
857fromIndices = fromStreamS . S.fromIndices
862-- fromIndicesM f = let g i = f i \`consM` g (i + 1) in g 0
865-- Generate an infinite stream, whose values are the output of a monadic
866-- function @f@ applied on the corresponding index. Index starts at 0.
871{-# INLINE_EARLY fromIndicesM #-}
872fromIndicesM :: (IsStream t, MonadAsync m) => (Int -> m a) -> t m a
873fromIndicesM = K.fromIndicesM
875{-# RULES "fromIndicesM serial" fromIndicesM = fromIndicesMSerial #-}
876{-# INLINE fromIndicesMSerial #-}
877fromIndicesMSerial :: MonadAsync m => (Int -> m a) -> SerialT m a
878fromIndicesMSerial = fromStreamS . S.fromIndicesM
882-- replicateM = take n . repeatM
885-- Generate a stream by performing a monadic action @n@ times. Same as:
888-- drain $ serially $ S.replicateM 10 $ (threadDelay 1000000 >> print 1)
889-- drain $ asyncly $ S.replicateM 10 $ (threadDelay 1000000 >> print 1)
895{-# INLINE_EARLY replicateM #-}
896replicateM :: (IsStream t, MonadAsync m) => Int -> m a -> t m a
897replicateM = K.replicateM
899{-# RULES "replicateM serial" replicateM = replicateMSerial #-}
900{-# INLINE replicateMSerial #-}
901replicateMSerial :: MonadAsync m => Int -> m a -> SerialT m a
902replicateMSerial n = fromStreamS . S.replicateM n
906-- replicate = take n . repeat
909-- Generate a stream of length @n@ by repeating a value @n@ times.
912{-# INLINE_NORMAL replicate #-}
913replicate :: (IsStream t, Monad m) => Int -> a -> t m a
914replicate n = fromStreamS . S.replicate n
917-- Generate an infinite stream by repeating a pure value.
920{-# INLINE_NORMAL repeat #-}
921repeat :: (IsStream t, Monad m) => a -> t m a
922repeat = fromStreamS . S.repeat
926-- repeatM = fix . consM
927-- repeatM = cycle1 . yieldM
930-- Generate a stream by repeatedly executing a monadic action forever.
933-- drain $ serially $ S.take 10 $ S.repeatM $ (threadDelay 1000000 >> print 1)
934-- drain $ asyncly $ S.take 10 $ S.repeatM $ (threadDelay 1000000 >> print 1)
937-- /Concurrent, infinite (do not use with 'parallely')/
940{-# INLINE_EARLY repeatM #-}
941repeatM :: (IsStream t, MonadAsync m) => m a -> t m a
944{-# RULES "repeatM serial" repeatM = repeatMSerial #-}
945{-# INLINE repeatMSerial #-}
946repeatMSerial :: MonadAsync m => m a -> SerialT m a
947repeatMSerial = fromStreamS . S.repeatM
951-- iterate f x = x \`cons` iterate f x
954-- Generate an infinite stream with @x@ as the first element and each
955-- successive element derived by applying the function @f@ on the previous
959-- > S.toList $ S.take 5 $ S.iterate (+1) 1
964{-# INLINE_NORMAL iterate #-}
965iterate :: (IsStream t, Monad m) => (a -> a) -> a -> t m a
966iterate step = fromStreamS . S.iterate step
970-- iterateM f m = m >>= \a -> return a \`consM` iterateM f (f a)
973-- Generate an infinite stream with the first element generated by the action
974-- @m@ and each successive element derived by applying the monadic function
975-- @f@ on the previous element.
977-- When run concurrently, the next iteration can run concurrently with the
978-- processing of the previous iteration. Note that more than one iteration
979-- cannot run concurrently as the next iteration depends on the output of the
980-- previous iteration.
983-- drain $ serially $ S.take 10 $ S.iterateM
984-- (\\x -> threadDelay 1000000 >> print x >> return (x + 1)) (return 0)
986-- drain $ asyncly $ S.take 10 $ S.iterateM
987-- (\\x -> threadDelay 1000000 >> print x >> return (x + 1)) (return 0)
994-- /Since: 0.7.0 (signature change)/
995{-# INLINE_EARLY iterateM #-}
996iterateM :: (IsStream t, MonadAsync m) => (a -> m a) -> m a -> t m a
999{-# RULES "iterateM serial" iterateM = iterateMSerial #-}
1000{-# INLINE iterateMSerial #-}
1001iterateMSerial :: MonadAsync m => (a -> m a) -> m a -> SerialT m a
1002iterateMSerial step = fromStreamS . S.iterateM step
1004------------------------------------------------------------------------------
1006------------------------------------------------------------------------------
1010-- fromListM = 'Prelude.foldr' 'K.consM' 'K.nil'
1013-- Construct a stream from a list of monadic actions. This is more efficient
1014-- than 'fromFoldableM' for serial streams.
1017{-# INLINE_EARLY fromListM #-}
1018fromListM :: (MonadAsync m, IsStream t) => [m a] -> t m a
1019fromListM = fromStreamD . D.fromListM
1020{-# RULES "fromListM fallback to StreamK" [1]
1021 forall a. D.toStreamK (D.fromListM a) = fromFoldableM a #-}
1025-- fromFoldableM = 'Prelude.foldr' 'consM' 'K.nil'
1028-- Construct a stream from a 'Foldable' containing monadic actions.
1031-- drain $ serially $ S.fromFoldableM $ replicateM 10 (threadDelay 1000000 >> print 1)
1032-- drain $ asyncly $ S.fromFoldableM $ replicateM 10 (threadDelay 1000000 >> print 1)
1035-- /Concurrent (do not use with 'parallely' on infinite containers)/
1038{-# INLINE fromFoldableM #-}
1039fromFoldableM :: (IsStream t, MonadAsync m, Foldable f) => f (m a) -> t m a
1040fromFoldableM = Prelude.foldr consM K.nil
1042-- | Same as 'fromFoldable'.
1045{-# DEPRECATED each "Please use fromFoldable instead." #-}
1047each :: (IsStream t, Foldable f) => f a -> t m a
1048each = K.fromFoldable
1050-- | Read lines from an IO Handle into a stream of Strings.
1053{-# DEPRECATED fromHandle
1054 "Please use Streamly.FileSystem.Handle module (see the changelog)" #-}
1055fromHandle :: (IsStream t, MonadIO m) => IO.Handle -> t m String
1058 go = K.mkStream $ \_ yld _ stp -> do
1059 eof <- liftIO $ IO.hIsEOF h
1063 str <- liftIO $ IO.hGetLine h
1066-- | Construct a stream by reading a 'Prim' 'IORef' repeatedly.
1070{-# INLINE fromPrimIORef #-}
1071fromPrimIORef :: (IsStream t, MonadIO m, Prim a) => IORef a -> t m a
1072fromPrimIORef = fromStreamD . D.fromPrimIORef
1074-- | Takes a callback setter function and provides it with a callback. The
1075-- callback when invoked adds a value at the tail of the stream. Returns a
1076-- stream of values generated by the callback.
1080{-# INLINE fromCallback #-}
1081fromCallback :: MonadAsync m => ((a -> m ()) -> m ()) -> SerialT m a
1082fromCallback setCallback = concatM $ do
1083 (callback, stream) <- D.newCallbackStream
1084 setCallback callback
1087------------------------------------------------------------------------------
1089------------------------------------------------------------------------------
1091-- | @timesWith g@ returns a stream of time value tuples. The first component
1092-- of the tuple is an absolute time reference (epoch) denoting the start of the
1093-- stream and the second component is a time relative to the reference.
1095-- The argument @g@ specifies the granularity of the relative time in seconds.
1096-- A lower granularity clock gives higher precision but is more expensive in
1097-- terms of CPU usage. Any granularity lower than 1 ms is treated as 1 ms.
1100-- >>> S.mapM_ (\x -> print x >> threadDelay 1000000) $ S.timesWith 0.01
1101-- > (AbsTime (TimeSpec {sec = 2496295, nsec = 536223000}),RelTime64 (NanoSecond64 0))
1102-- > (AbsTime (TimeSpec {sec = 2496295, nsec = 536223000}),RelTime64 (NanoSecond64 1002028000))
1103-- > (AbsTime (TimeSpec {sec = 2496295, nsec = 536223000}),RelTime64 (NanoSecond64 1996656000))
1106-- Note: This API is not safe on 32-bit machines.
1110{-# INLINE timesWith #-}
1111timesWith :: (IsStream t, MonadAsync m) => Double -> t m (AbsTime, RelTime64)
1112timesWith g = fromStreamD $ D.times g
1114-- | @times@ returns a stream of time value tuples with clock of 10 ms
1115-- granularity. The first component of the tuple is an absolute time reference
1116-- (epoch) denoting the start of the stream and the second component is a time
1117-- relative to the reference.
1120-- >>> S.mapM_ (\x -> print x >> threadDelay 1000000) $ S.times
1121-- > (AbsTime (TimeSpec {sec = 2496295, nsec = 536223000}),RelTime64 (NanoSecond64 0))
1122-- > (AbsTime (TimeSpec {sec = 2496295, nsec = 536223000}),RelTime64 (NanoSecond64 1002028000))
1123-- > (AbsTime (TimeSpec {sec = 2496295, nsec = 536223000}),RelTime64 (NanoSecond64 1996656000))
1126-- Note: This API is not safe on 32-bit machines.
1131times :: (IsStream t, MonadAsync m) => t m (AbsTime, RelTime64)
1132times = timesWith 0.01
1134-- | @absTimesWith g@ returns a stream of absolute timestamps using a clock of
1135-- granularity @g@ specified in seconds. A low granularity clock is more
1136-- expensive in terms of CPU usage. Any granularity lower than 1 ms is treated
1140-- >>> S.mapM_ print $ S.delayPre 1 $ S.absTimesWith 0.01
1143-- Note: This API is not safe on 32-bit machines.
1147{-# INLINE absTimesWith #-}
1148absTimesWith :: (IsStream t, MonadAsync m, Functor (t m))
1149 => Double -> t m AbsTime
1150absTimesWith = fmap (uncurry addToAbsTime64) . timesWith
1152-- | @absTimes@ returns a stream of absolute timestamps using a clock of 10 ms
1156-- >>> S.mapM_ print $ S.delayPre 1 $ S.absTimes
1159-- Note: This API is not safe on 32-bit machines.
1163{-# INLINE absTimes #-}
1164absTimes :: (IsStream t, MonadAsync m, Functor (t m)) => t m AbsTime
1165absTimes = fmap (uncurry addToAbsTime64) times
1167{-# DEPRECATED currentTime "Please use absTimes instead" #-}
1168{-# INLINE currentTime #-}
1169currentTime :: (IsStream t, MonadAsync m, Functor (t m))
1170 => Double -> t m AbsTime
1171currentTime = absTimesWith
1173-- | @relTimesWith g@ returns a stream of relative time values starting from 0,
1174-- using a clock of granularity @g@ specified in seconds. A low granularity
1175-- clock is more expensive in terms of CPU usage. Any granularity lower than 1
1176-- ms is treated as 1 ms.
1179-- >>> S.mapM_ print $ S.delayPre 1 $ S.relTimesWith 0.01
1180-- > RelTime64 (NanoSecond64 0)
1181-- > RelTime64 (NanoSecond64 91139000)
1182-- > RelTime64 (NanoSecond64 204052000)
1185-- Note: This API is not safe on 32-bit machines.
1189{-# INLINE relTimesWith #-}
1190relTimesWith :: (IsStream t, MonadAsync m, Functor (t m))
1191 => Double -> t m RelTime64
1192relTimesWith = fmap snd . timesWith
1194-- | @relTimes@ returns a stream of relative time values starting from 0,
1195-- using a clock of granularity 10 ms.
1198-- >>> S.mapM_ print $ S.delayPre 1 $ S.relTimes
1201-- Note: This API is not safe on 32-bit machines.
1205{-# INLINE relTimes #-}
1206relTimes :: (IsStream t, MonadAsync m, Functor (t m)) => t m RelTime64
1207relTimes = fmap snd times
1209-- | @durations g@ returns a stream of relative time values measuring the time
1210-- elapsed since the immediate predecessor element of the stream was generated.
1211-- The first element of the stream is always 0. @durations@ uses a clock of
1212-- granularity @g@ specified in seconds. A low granularity clock is more
1213-- expensive in terms of CPU usage. The minimum granularity is 1 millisecond.
1214-- Durations lower than 1 ms will be 0.
1216-- Note: This API is not safe on 32-bit machines.
1220{-# INLINE durations #-}
1221durations :: -- (IsStream t, MonadAsync m) =>
1222 Double -> t m RelTime64
1223durations = undefined
1225-- | Generate ticks at the specified rate. The rate is adaptive, the tick
1226-- generation speed can be increased or decreased at different times to achieve
1227-- the specified rate. The specific behavior for different styles of 'Rate'
1228-- specifications is documented under 'Rate'. The effective maximum rate
1229-- achieved by a stream is governed by the processor speed.
1234ticks :: -- (IsStream t, MonadAsync m) =>
1238-- | Generate a singleton event at or after the specified absolute time. Note
1239-- that this is different from a threadDelay, a threadDelay starts from the
1240-- time when the action is evaluated, whereas if we use AbsTime based timeout
1241-- it will immediately expire if the action is evaluated too late.
1245{-# INLINE timeout #-}
1246timeout :: -- (IsStream t, MonadAsync m) =>
1250------------------------------------------------------------------------------
1251-- Elimination by Folding
1252------------------------------------------------------------------------------
1254-- | Right associative/lazy pull fold. @foldrM build final stream@ constructs
1255-- an output structure using the step function @build@. @build@ is invoked with
1256-- the next input element and the remaining (lazy) tail of the output
1257-- structure. It builds a lazy output expression using the two. When the "tail
1258-- structure" in the output expression is evaluated it calls @build@ again thus
1259-- lazily consuming the input @stream@ until either the output expression built
1260-- by @build@ is free of the "tail" or the input is exhausted in which case
1261-- @final@ is used as the terminating case for the output structure. For more
1262-- details see the description in the previous section.
1264-- Example, determine if any element is 'odd' in a stream:
1266-- >>> S.foldrM (\x xs -> if odd x then return True else xs) (return False) $ S.fromList (2:4:5:undefined)
1269-- /Since: 0.7.0 (signature changed)/
1271-- /Since: 0.2.0 (signature changed)/
1274{-# INLINE foldrM #-}
1275foldrM :: Monad m => (a -> m b -> m b) -> m b -> SerialT m a -> m b
1278-- | Right fold to a streaming monad.
1280-- > foldrS S.cons S.nil === id
1282-- 'foldrS' can be used to perform stateless stream to stream transformations
1283-- like map and filter in general. It can be coupled with a scan to perform
1284-- stateful transformations. However, note that the custom map and filter
1285-- routines can be much more efficient than this due to better stream fusion.
1287-- >>> S.toList $ S.foldrS S.cons S.nil $ S.fromList [1..5]
1290-- Find if any element in the stream is 'True':
1292-- >>> S.toList $ S.foldrS (\x xs -> if odd x then return True else xs) (return False) $ (S.fromList (2:4:5:undefined) :: SerialT IO Int)
1295-- Map (+2) on odd elements and filter out the even elements:
1297-- >>> S.toList $ S.foldrS (\x xs -> if odd x then (x + 2) `S.cons` xs else xs) S.nil $ (S.fromList [1..5] :: SerialT IO Int)
1300-- 'foldrM' can also be represented in terms of 'foldrS', however, the former
1301-- is much more efficient:
1303-- > foldrM f z s = runIdentityT $ foldrS (\x xs -> lift $ f x (runIdentityT xs)) (lift z) s
1306{-# INLINE foldrS #-}
1307foldrS :: IsStream t => (a -> t m b -> t m b) -> t m b -> t m a -> t m b
1310-- | Right fold to a transformer monad. This is the most general right fold
1311-- function. 'foldrS' is a special case of 'foldrT', however 'foldrS'
1312-- implementation can be more efficient:
1315-- > foldrM f z s = runIdentityT $ foldrT (\x xs -> lift $ f x (runIdentityT xs)) (lift z) s
1317-- 'foldrT' can be used to translate streamly streams to other transformer
1318-- monads e.g. to a different streaming type.
1321{-# INLINE foldrT #-}
1322foldrT :: (IsStream t, Monad m, Monad (s m), MonadTrans s)
1323 => (a -> s m b -> s m b) -> s m b -> t m a -> s m b
1324foldrT f z s = S.foldrT f z (toStreamS s)
1326-- | Right fold, lazy for lazy monads and pure streams, and strict for strict
1329-- Please avoid using this routine in strict monads like IO unless you need a
1330-- strict right fold. This is provided only for use in lazy monads (e.g.
1331-- Identity) or pure streams. Note that with this signature it is not possible
1332-- to implement a lazy foldr when the monad @m@ is strict. In that case it
1333-- would be strict in its accumulator and therefore would necessarily consume
1338foldr :: Monad m => (a -> b -> b) -> b -> SerialT m a -> m b
1341-- XXX This seems to be of limited use as it cannot be used to construct
1342-- recursive structures and for reduction foldl1' is better.
1344-- | Lazy right fold for non-empty streams, using first element as the starting
1345-- value. Returns 'Nothing' if the stream is empty.
1348{-# INLINE foldr1 #-}
1349{-# DEPRECATED foldr1 "Use foldrM instead." #-}
1350foldr1 :: Monad m => (a -> a -> a) -> SerialT m a -> m (Maybe a)
1351foldr1 f m = S.foldr1 f (toStreamS m)
1353-- | Strict left fold with an extraction function. Like the standard strict
1354-- left fold, but applies a user supplied extraction function (the third
1355-- argument) to the folded value at the end. This is designed to work with the
1356-- @foldl@ library. The suffix @x@ is a mnemonic for extraction.
1359{-# DEPRECATED foldx "Please use foldl' followed by fmap instead." #-}
1361foldx :: Monad m => (x -> a -> x) -> x -> (x -> b) -> SerialT m a -> m b
1364-- | Left associative/strict push fold. @foldl' reduce initial stream@ invokes
1365-- @reduce@ with the accumulator and the next input in the input stream, using
1366-- @initial@ as the initial value of the current value of the accumulator. When
1367-- the input is exhausted the current value of the accumulator is returned.
1368-- Make sure to use a strict data structure for accumulator to not build
1369-- unnecessary lazy expressions unless that's what you want. See the previous
1370-- section for more details.
1373{-# INLINE foldl' #-}
1374foldl' :: Monad m => (b -> a -> b) -> b -> SerialT m a -> m b
1377-- | Strict left fold, for non-empty streams, using first element as the
1378-- starting value. Returns 'Nothing' if the stream is empty.
1381{-# INLINE foldl1' #-}
1382foldl1' :: Monad m => (a -> a -> a) -> SerialT m a -> m (Maybe a)
1386 Nothing -> return Nothing
1388 res <- foldl' step h t
1391-- | Like 'foldx', but with a monadic step function.
1394{-# DEPRECATED foldxM "Please use foldlM' followed by fmap instead." #-}
1395{-# INLINE foldxM #-}
1396foldxM :: Monad m => (x -> a -> m x) -> m x -> (x -> m b) -> SerialT m a -> m b
1399-- | Like 'foldl'' but with a monadic step function.
1402{-# INLINE foldlM' #-}
1403foldlM' :: Monad m => (b -> a -> m b) -> m b -> SerialT m a -> m b
1404foldlM' step begin m = S.foldlM' step begin $ toStreamS m
1406------------------------------------------------------------------------------
1408------------------------------------------------------------------------------
1410-- | Fold a stream using the supplied left fold.
1412-- >>> S.fold FL.sum (S.enumerateFromTo 1 100)
1417fold :: Monad m => Fold m a b -> SerialT m a -> m b
1420------------------------------------------------------------------------------
1422------------------------------------------------------------------------------
1425-- | Drain a stream to a 'Sink'.
1426{-# INLINE runSink #-}
1427runSink :: Monad m => Sink m a -> SerialT m a -> m ()
1428runSink = fold . toFold
1431------------------------------------------------------------------------------
1433------------------------------------------------------------------------------
1435-- | Parse a stream using the supplied 'Parser'.
1439{-# INLINE_NORMAL parseD #-}
1440parseD :: MonadThrow m => PRD.Parser m a b -> SerialT m a -> m b
1441parseD (PRD.Parser step initial extract) = P.parselMx' step initial extract
1443{-# INLINE parseK #-}
1444parseK :: MonadThrow m => PRK.Parser m a b -> SerialT m a -> m b
1447-- | Parse a stream using the supplied 'Parser'.
1451{-# INLINE [3] parse #-}
1452parse :: MonadThrow m => Parser m a b -> SerialT m a -> m b
1453parse = parseD . PRK.fromParserK
1455------------------------------------------------------------------------------
1457------------------------------------------------------------------------------
1460-- > drain = mapM_ (\_ -> return ())
1462-- Run a stream, discarding the results. By default it interprets the stream
1463-- as 'SerialT', to run other types of streams use the type adapting
1464-- combinators for example @drain . 'asyncly'@.
1468drain :: Monad m => SerialT m a -> m ()
1471-- | Run a stream, discarding the results. By default it interprets the stream
1472-- as 'SerialT', to run other types of streams use the type adapting
1473-- combinators for example @runStream . 'asyncly'@.
1476{-# DEPRECATED runStream "Please use \"drain\" instead" #-}
1477{-# INLINE runStream #-}
1478runStream :: Monad m => SerialT m a -> m ()
1482-- > drainN n = drain . take n
1484-- Run maximum up to @n@ iterations of a stream.
1487{-# INLINE drainN #-}
1488drainN :: Monad m => Int -> SerialT m a -> m ()
1489drainN n = drain . take n
1492-- > runN n = runStream . take n
1494-- Run maximum up to @n@ iterations of a stream.
1497{-# DEPRECATED runN "Please use \"drainN\" instead" #-}
1499runN :: Monad m => Int -> SerialT m a -> m ()
1503-- > drainWhile p = drain . takeWhile p
1505-- Run a stream as long as the predicate holds true.
1508{-# INLINE drainWhile #-}
1509drainWhile :: Monad m => (a -> Bool) -> SerialT m a -> m ()
1510drainWhile p = drain . takeWhile p
1513-- > runWhile p = runStream . takeWhile p
1515-- Run a stream as long as the predicate holds true.
1518{-# DEPRECATED runWhile "Please use \"drainWhile\" instead" #-}
1519{-# INLINE runWhile #-}
1520runWhile :: Monad m => (a -> Bool) -> SerialT m a -> m ()
1521runWhile = drainWhile
1523-- | Determine whether the stream is empty.
1527null :: Monad m => SerialT m a -> m Bool
1528null = S.null . toStreamS
1530-- | Extract the first element of the stream, if any.
1536head :: Monad m => SerialT m a -> m (Maybe a)
1537head = S.head . toStreamS
1539-- | Extract the first element of the stream, if any, otherwise use the
1540-- supplied default value. It can help avoid one branch in high performance
1544{-# INLINE headElse #-}
1545headElse :: Monad m => a -> SerialT m a -> m a
1546headElse x = D.headElse x . toStreamD
1549-- > tail = fmap (fmap snd) . uncons
1551-- Extract all but the first element of the stream, if any.
1555tail :: (IsStream t, Monad m) => SerialT m a -> m (Maybe (t m a))
1556tail m = K.tail (K.adapt m)
1558-- | Extract all but the last element of the stream, if any.
1562init :: (IsStream t, Monad m) => SerialT m a -> m (Maybe (t m a))
1563init m = K.init (K.adapt m)
1565-- | Extract the last element of the stream, if any.
1567-- > last xs = xs !! (length xs - 1)
1571last :: Monad m => SerialT m a -> m (Maybe a)
1572last m = S.last $ toStreamS m
1574-- | Determine whether an element is present in the stream.
1578elem :: (Monad m, Eq a) => a -> SerialT m a -> m Bool
1579elem e m = S.elem e (toStreamS m)
1581-- | Determine whether an element is not present in the stream.
1584{-# INLINE notElem #-}
1585notElem :: (Monad m, Eq a) => a -> SerialT m a -> m Bool
1586notElem e m = S.notElem e (toStreamS m)
1588-- | Determine the length of the stream.
1591{-# INLINE length #-}
1592length :: Monad m => SerialT m a -> m Int
1593length = foldl' (\n _ -> n + 1) 0
1595-- | Determine whether all elements of a stream satisfy a predicate.
1599all :: Monad m => (a -> Bool) -> SerialT m a -> m Bool
1600all p m = S.all p (toStreamS m)
1602-- | Determine whether any of the elements of a stream satisfy a predicate.
1606any :: Monad m => (a -> Bool) -> SerialT m a -> m Bool
1607any p m = S.any p (toStreamS m)
1609-- | Determines if all elements of a boolean stream are True.
1613and :: Monad m => SerialT m Bool -> m Bool
1616-- | Determines whether at least one element of a boolean stream is True.
1620or :: Monad m => SerialT m Bool -> m Bool
1623-- | Determine the sum of all elements of a stream of numbers. Returns @0@ when
1624-- the stream is empty. Note that this is not numerically stable for floating
1629sum :: (Monad m, Num a) => SerialT m a -> m a
1632-- | Determine the product of all elements of a stream of numbers. Returns @1@
1633-- when the stream is empty.
1636{-# INLINE product #-}
1637product :: (Monad m, Num a) => SerialT m a -> m a
1638product = foldl' (*) 1
1640-- | Fold a stream of monoid elements by appending them.
1643{-# INLINE mconcat #-}
1644mconcat :: (Monad m, Monoid a) => SerialT m a -> m a
1645mconcat = foldr mappend mempty
1649-- minimum = 'minimumBy' compare
1652-- Determine the minimum element in a stream.
1655{-# INLINE minimum #-}
1656minimum :: (Monad m, Ord a) => SerialT m a -> m (Maybe a)
1657minimum m = S.minimum (toStreamS m)
1659-- | Determine the minimum element in a stream using the supplied comparison
1663{-# INLINE minimumBy #-}
1664minimumBy :: Monad m => (a -> a -> Ordering) -> SerialT m a -> m (Maybe a)
1665minimumBy cmp m = S.minimumBy cmp (toStreamS m)
1669-- maximum = 'maximumBy' compare
1672-- Determine the maximum element in a stream.
1675{-# INLINE maximum #-}
1676maximum :: (Monad m, Ord a) => SerialT m a -> m (Maybe a)
1679-- | Determine the maximum element in a stream using the supplied comparison
1683{-# INLINE maximumBy #-}
1684maximumBy :: Monad m => (a -> a -> Ordering) -> SerialT m a -> m (Maybe a)
1685maximumBy cmp m = S.maximumBy cmp (toStreamS m)
1687-- | Lookup the element at the given index.
1691(!!) :: Monad m => SerialT m a -> Int -> m (Maybe a)
1692m !! i = toStreamS m S.!! i
1694-- | In a stream of (key-value) pairs @(a, b)@, return the value @b@ of the
1695-- first pair where the key equals the given value @a@.
1697-- > lookup = snd <$> find ((==) . fst)
1700{-# INLINE lookup #-}
1701lookup :: (Monad m, Eq a) => a -> SerialT m (a, b) -> m (Maybe b)
1702lookup a m = S.lookup a (toStreamS m)
1704-- | Like 'findM' but with a non-monadic predicate.
1706-- > find p = findM (return . p)
1710find :: Monad m => (a -> Bool) -> SerialT m a -> m (Maybe a)
1711find p m = S.find p (toStreamS m)
1713-- | Returns the first element that satisfies the given predicate.
1717findM :: Monad m => (a -> m Bool) -> SerialT m a -> m (Maybe a)
1718findM p m = S.findM p (toStreamS m)
1720-- | Find all the indices where the element in the stream satisfies the given
1724{-# INLINE findIndices #-}
1725findIndices :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m Int
1726findIndices p m = fromStreamS $ S.findIndices p (toStreamS m)
1728-- | Returns the first index that satisfies the given predicate.
1731{-# INLINE findIndex #-}
1732findIndex :: Monad m => (a -> Bool) -> SerialT m a -> m (Maybe Int)
1733findIndex p = head . findIndices p
1735-- | Find all the indices where the value of the element in the stream is equal
1736-- to the given value.
1739{-# INLINE elemIndices #-}
1740elemIndices :: (IsStream t, Eq a, Monad m) => a -> t m a -> t m Int
1741elemIndices a = findIndices (==a)
1743-- | Returns the first index where a given value is found in the stream.
1745-- > elemIndex a = findIndex (== a)
1748{-# INLINE elemIndex #-}
1749elemIndex :: (Monad m, Eq a) => a -> SerialT m a -> m (Maybe Int)
1750elemIndex a = findIndex (== a)
1752------------------------------------------------------------------------------
1754------------------------------------------------------------------------------
1756-- | Returns 'True' if the first stream is the same as or a prefix of the
1757-- second. A stream is a prefix of itself.
1760-- > S.isPrefixOf (S.fromList "hello") (S.fromList "hello" :: SerialT IO Char)
1765{-# INLINE isPrefixOf #-}
1766isPrefixOf :: (Eq a, IsStream t, Monad m) => t m a -> t m a -> m Bool
1767isPrefixOf m1 m2 = D.isPrefixOf (toStreamD m1) (toStreamD m2)
1769-- Note: isPrefixOf uses the prefix stream only once. In contrast, isSuffixOf
1770-- may use the suffix stream many times. To run in optimal memory we do not
1771-- want to buffer the suffix stream in memory therefore we need an ability to
1772-- clone (or consume it multiple times) the suffix stream without any side
1773-- effects so that multiple potential suffix matches can proceed in parallel
1774-- without buffering the suffix stream. For example, we may create the suffix
1775-- stream from a file handle, however, if we evaluate the stream multiple
1776-- times, once for each match, we will need a different file handle each time
1777-- which may exhaust the file descriptors. Instead, we want to share the same
1778-- underlying file descriptor, use pread on it to generate the stream and clone
1779-- the stream for each match. Therefore the suffix stream should be built in
1780-- such a way that it can be consumed multiple times without any problems.
1782-- XXX Can be implemented with better space/time complexity.
1783-- Space: @O(n)@ worst case where @n@ is the length of the suffix.
1785-- | Returns 'True' if the first stream is a suffix of the second. A stream is
1786-- considered a suffix of itself.
1789-- > S.isSuffixOf (S.fromList "hello") (S.fromList "hello" :: SerialT IO Char)
1793-- Space: @O(n)@, buffers entire input stream and the suffix.
1797-- /Suboptimal/ - Help wanted.
1799{-# INLINE isSuffixOf #-}
1800isSuffixOf :: (Monad m, Eq a) => SerialT m a -> SerialT m a -> m Bool
1801isSuffixOf suffix stream = reverse suffix `isPrefixOf` reverse stream
1803-- | Returns 'True' if the first stream is an infix of the second. A stream is
1804-- considered an infix of itself.
1807-- > S.isInfixOf (S.fromList "hello") (S.fromList "hello" :: SerialT IO Char)
1811-- Space: @O(n)@ worst case where @n@ is the length of the infix.
1815-- /Requires 'Storable' constraint/ - Help wanted.
1817{-# INLINE isInfixOf #-}
1818isInfixOf :: (MonadIO m, Eq a, Enum a, Storable a)
1819 => SerialT m a -> SerialT m a -> m Bool
1820isInfixOf infx stream = do
1821 arr <- fold A.write infx
1822 -- XXX can use breakOnSeq instead (when available)
1823 r <- null $ drop 1 $ splitOnSeq arr FL.drain stream
1826-- | Returns 'True' if all the elements of the first stream occur, in order, in
1827-- the second stream. The elements do not have to occur consecutively. A stream
1828-- is a subsequence of itself.
1831-- > S.isSubsequenceOf (S.fromList "hlo") (S.fromList "hello" :: SerialT IO Char)
1836{-# INLINE isSubsequenceOf #-}
1837isSubsequenceOf :: (Eq a, IsStream t, Monad m) => t m a -> t m a -> m Bool
1838isSubsequenceOf m1 m2 = D.isSubsequenceOf (toStreamD m1) (toStreamD m2)
1840-- | Strip prefix if present and tell whether it was stripped or not. Returns
1841-- 'Nothing' if the stream does not start with the given prefix, stripped
1842-- stream otherwise. Returns @Just nil@ when the prefix is the same as the
1848{-# INLINE stripPrefix #-}
1850 :: (Eq a, IsStream t, Monad m)
1851 => t m a -> t m a -> m (Maybe (t m a))
1852stripPrefix m1 m2 = fmap fromStreamD <$>
1853 D.stripPrefix (toStreamD m1) (toStreamD m2)
1855-- Note: If we want to return a Maybe value to know whether the
1856-- suffix/infix was present or not along with the stripped stream then
1857-- we need to buffer the whole input stream.
1859-- | Drops the given suffix from a stream. Returns 'Nothing' if the stream does
1860-- not end with the given suffix. Returns @Just nil@ when the suffix is the
1861-- same as the stream.
1863-- It may be more efficient to convert the stream to an Array and use
1864-- stripSuffix on that especially if the elements have a Storable or Prim
1867-- Space: @O(n)@, buffers the entire input stream as well as the suffix
1870{-# INLINE stripSuffix #-}
1873 => SerialT m a -> SerialT m a -> m (Maybe (SerialT m a))
1874stripSuffix m1 m2 = fmap reverse <$> stripPrefix (reverse m1) (reverse m2)
1876-- | Drop prefix from the input stream if present.
1880-- /Unimplemented/ - Help wanted.
1881{-# INLINE dropPrefix #-}
1883 -- (Eq a, IsStream t, Monad m) =>
1884 t m a -> t m a -> t m a
1885dropPrefix = error "Not implemented yet!"
1887-- | Drop all matching infix from the input stream if present. Infix stream
1888-- may be consumed multiple times.
1890-- Space: @O(n)@ where n is the length of the infix.
1892-- /Unimplemented/ - Help wanted.
1893{-# INLINE dropInfix #-}
1895 -- (Eq a, IsStream t, Monad m) =>
1896 t m a -> t m a -> t m a
1897dropInfix = error "Not implemented yet!"
1899-- | Drop suffix from the input stream if present. Suffix stream may be
1900-- consumed multiple times.
1902-- Space: @O(n)@ where n is the length of the suffix.
1904-- /Unimplemented/ - Help wanted.
1905{-# INLINE dropSuffix #-}
1907 -- (Eq a, IsStream t, Monad m) =>
1908 t m a -> t m a -> t m a
1909dropSuffix = error "Not implemented yet!"
1911------------------------------------------------------------------------------
1913------------------------------------------------------------------------------
1915-- XXX this can utilize parallel mapping if we implement it as drain . mapM
1917-- > mapM_ = drain . mapM
1919-- Apply a monadic action to each element of the stream and discard the output
1920-- of the action. This is not really a pure transformation operation but a
1921-- transformation followed by fold.
1925mapM_ :: Monad m => (a -> m b) -> SerialT m a -> m ()
1926mapM_ f m = S.mapM_ f $ toStreamS m
1928------------------------------------------------------------------------------
1930------------------------------------------------------------------------------
1934-- toList = S.foldr (:) []
1937-- Convert a stream into a list in the underlying monad. The list can be
1938-- consumed lazily in a lazy monad (e.g. 'Identity'). In a strict monad (e.g.
1939-- IO) the whole list is generated and buffered before it can be consumed.
1941-- /Warning!/ working on large lists accumulated as buffers in memory could be
1942-- very inefficient, consider using "Streamly.Array" instead.
1945{-# INLINE toList #-}
1946toList :: Monad m => SerialT m a -> m [a]
1951-- toListRev = S.foldl' (flip (:)) []
1954-- Convert a stream into a list in reverse order in the underlying monad.
1956-- /Warning!/ working on large lists accumulated as buffers in memory could be
1957-- very inefficient, consider using "Streamly.Array" instead.
1960{-# INLINE toListRev #-}
1961toListRev :: Monad m => SerialT m a -> m [a]
1962toListRev = D.toListRev . toStreamD
1966-- toHandle h = S.mapM_ $ hPutStrLn h
1969-- Write a stream of Strings to an IO Handle.
1972{-# DEPRECATED toHandle
1973 "Please use Streamly.FileSystem.Handle module (see the changelog)" #-}
1974toHandle :: MonadIO m => IO.Handle -> SerialT m String -> m ()
1978 let stop = return ()
1979 single a = liftIO (IO.hPutStrLn h a)
1980 yieldk a r = liftIO (IO.hPutStrLn h a) >> go r
1981 in K.foldStream defState yieldk single stop m1
1983-- XXX rename these to write/writeRev to make the naming consistent with folds
1986-- | A fold that buffers its input to a pure stream.
1988-- /Warning!/ working on large streams accumulated as buffers in memory could
1989-- be very inefficient, consider using "Streamly.Data.Array" instead.
1992{-# INLINE toStream #-}
1993toStream :: Monad m => Fold m a (SerialT Identity a)
1994toStream = Fold (\f x -> return $ f . (x `K.cons`))
1996 (return . ($ K.nil))
1998-- This is more efficient than 'toStream'. toStream is exactly the same as
1999-- reversing the stream after toStreamRev.
2001-- | Buffers the input stream to a pure stream in the reverse order of the
2004-- /Warning!/ working on large streams accumulated as buffers in memory could
2005-- be very inefficient, consider using "Streamly.Data.Array" instead.
2009-- xn : ... : x2 : x1 : []
2010{-# INLINABLE toStreamRev #-}
2011toStreamRev :: Monad m => Fold m a (SerialT Identity a)
2012toStreamRev = Fold (\xs x -> return $ x `K.cons` xs) (return K.nil) return
2014-- | Convert a stream to a pure stream.
2017-- toPure = foldr cons nil
2022{-# INLINE toPure #-}
2023toPure :: Monad m => SerialT m a -> m (SerialT Identity a)
2024toPure = foldr K.cons K.nil
2026-- | Convert a stream to a pure stream in reverse order.
2029-- toPureRev = foldl' (flip cons) nil
2034{-# INLINE toPureRev #-}
2035toPureRev :: Monad m => SerialT m a -> m (SerialT Identity a)
2036toPureRev = foldl' (flip K.cons) K.nil
2038------------------------------------------------------------------------------
2039-- Concurrent Application
2040------------------------------------------------------------------------------
2048-- | Parallel transform application operator; applies a stream transformation
2049-- function @t m a -> t m b@ to a stream @t m a@ concurrently; the input stream
2050-- is evaluated asynchronously in an independent thread yielding elements to a
2051-- buffer and the transformation function runs in another thread consuming the
2052-- input from the buffer. '|$' is just like regular function application
2053-- operator '$' except that it is concurrent.
2055-- If you read the signature as @(t m a -> t m b) -> (t m a -> t m b)@ you can
2056-- look at it as a transformation that converts a transform function to a
2057-- buffered concurrent transform function.
2059-- The following code prints a value every second even though each stage adds a
2065-- S.mapM (\\x -> threadDelay 1000000 >> print x)
2066-- |$ S.repeatM (threadDelay 1000000 >> return 1)
2071-- /Since: 0.3.0 ("Streamly")/
2075(|$) :: (IsStream t, MonadAsync m) => (t m a -> t m b) -> (t m a -> t m b)
2076-- (|$) f = f . Async.mkAsync
2077(|$) f = f . D.mkParallel
2083{-# INLINE applyAsync #-}
2084applyAsync :: (IsStream t, MonadAsync m)
2085 => (t m a -> t m b) -> (t m a -> t m b)
2088-- | Parallel reverse function application operator for streams; just like the
2089-- regular reverse function application operator '&' except that it is
2094-- S.repeatM (threadDelay 1000000 >> return 1)
2095-- |& S.mapM (\\x -> threadDelay 1000000 >> print x)
2100-- /Since: 0.3.0 ("Streamly")/
2104(|&) :: (IsStream t, MonadAsync m) => t m a -> (t m a -> t m b) -> t m b
2107-- | Parallel fold application operator; applies a fold function @t m a -> m b@
2108-- to a stream @t m a@ concurrently; The the input stream is evaluated
2109-- asynchronously in an independent thread yielding elements to a buffer and
2110-- the folding action runs in another thread consuming the input from the
2113-- If you read the signature as @(t m a -> m b) -> (t m a -> m b)@ you can look
2114-- at it as a transformation that converts a fold function to a buffered
2115-- concurrent fold function.
2117-- The @.@ at the end of the operator is a mnemonic for termination of the
2121-- S.foldlM' (\\_ a -> threadDelay 1000000 >> print a) ()
2122-- |$. S.repeatM (threadDelay 1000000 >> return 1)
2127-- /Since: 0.3.0 ("Streamly")/
2131(|$.) :: (IsStream t, MonadAsync m) => (t m a -> m b) -> (t m a -> m b)
2132-- (|$.) f = f . Async.mkAsync
2133(|$.) f = f . D.mkParallel
2139{-# INLINE foldAsync #-}
2140foldAsync :: (IsStream t, MonadAsync m) => (t m a -> m b) -> (t m a -> m b)
2143-- | Parallel reverse function application operator for applying a run or fold
2144-- functions to a stream. Just like '|$.' except that the operands are reversed.
2147-- S.repeatM (threadDelay 1000000 >> return 1)
2148-- |&. S.foldlM' (\\_ a -> threadDelay 1000000 >> print a) ()
2153-- /Since: 0.3.0 ("Streamly")/
2157(|&.) :: (IsStream t, MonadAsync m) => t m a -> (t m a -> m b) -> m b
2160------------------------------------------------------------------------------
2161-- General Transformation
2162------------------------------------------------------------------------------
2164-- | Use a 'Pipe' to transform a stream.
2168{-# INLINE transform #-}
2169transform :: (IsStream t, Monad m) => Pipe m a b -> t m a -> t m b
2170transform pipe xs = fromStreamD $ D.transform pipe (toStreamD xs)
2172------------------------------------------------------------------------------
2173-- Transformation by Folding (Scans)
2174------------------------------------------------------------------------------
2176-- XXX It may be useful to have a version of scan where we can keep the
2177-- accumulator independent of the value emitted. So that we do not necessarily
2178-- have to keep a value in the accumulator which we are not using. We can pass
2179-- an extraction function that will take the accumulator and the current value
2180-- of the element and emit the next value in the stream. That will also make it
2181-- possible to modify the accumulator after using it. In fact, the step function
2182-- can return new accumulator and the value to be emitted. The signature would
2183-- be more like mapAccumL. Or we can change the signature of scanx to
2186-- | Strict left scan with an extraction function. Like 'scanl'', but applies a
2187-- user supplied extraction function (the third argument) at each step. This is
2188-- designed to work with the @foldl@ library. The suffix @x@ is a mnemonic for
2193-- /Since: 0.7.0 (Monad m constraint)/
2194{-# DEPRECATED scanx "Please use scanl followed by map instead." #-}
2196scanx :: (IsStream t, Monad m) => (x -> a -> x) -> x -> (x -> b) -> t m a -> t m b
2199-- XXX this needs to be concurrent
2200-- XXX because of the use of D.cons for appending, scanlM' has quadratic
2201-- complexity when iterated over a stream. We should use StreamK style scanlM'
2202-- for linear performance on iteration.
2204-- | Like 'scanl'' but with a monadic step function and a monadic seed.
2208-- /Since: 0.8.0 (signature change)/
2209{-# INLINE scanlM' #-}
2210scanlM' :: (IsStream t, Monad m) => (b -> a -> m b) -> m b -> t m a -> t m b
2211scanlM' step begin m = fromStreamD $ D.scanlM' step begin $ toStreamD m
2213-- | @scanlMAfter' accumulate initial done stream@ is like 'scanlM'' except
2214-- that it provides an additional @done@ function to be applied on the
2215-- accumulator when the stream stops. The result of @done@ is also emitted in
2218-- This function can be used to allocate a resource in the beginning of the
2219-- scan and release it when the stream ends or to flush the internal state of
2220-- the scan at the end.
2224{-# INLINE scanlMAfter' #-}
2225scanlMAfter' :: (IsStream t, Monad m)
2226 => (b -> a -> m b) -> m b -> (b -> m b) -> t m a -> t m b
2227scanlMAfter' step initial done stream =
2228 fromStreamD $ D.scanlMAfter' step initial done $ toStreamD stream
2230-- XXX because of the use of D.cons for appending, scanl' has quadratic
2231-- complexity when iterated over a stream. We should use StreamK style scanlM'
2232-- for linear performance on iteration.
2234-- | Strict left scan. Like 'map', 'scanl'' too is a one to one transformation,
2235-- however it adds an extra element.
2238-- > S.toList $ S.scanl' (+) 0 $ fromList [1,2,3,4]
2243-- > S.toList $ S.scanl' (flip (:)) [] $ S.fromList [1,2,3,4]
2244-- [[],[1],[2,1],[3,2,1],[4,3,2,1]]
2247-- The output of 'scanl'' is the initial value of the accumulator followed by
2248-- all the intermediate steps and the final result of 'foldl''.
2250-- By streaming the accumulated state after each fold step, we can share the
2251-- state across multiple stages of stream composition. Each stage can modify or
2252-- extend the state, do some processing with it and emit it for the next stage,
2253-- thus modularizing the stream processing. This can be useful in
2254-- stateful or event-driven programming.
2256-- Consider the following monolithic example, computing the sum and the product
2257-- of the elements in a stream in one go using a @foldl'@:
2260-- > S.foldl' (\\(s, p) x -> (s + x, p * x)) (0,1) $ S.fromList \[1,2,3,4]
2264-- Using @scanl'@ we can make it modular by computing the sum in the first
2265-- stage and passing it down to the next stage for computing the product:
2268-- > S.foldl' (\\(_, p) (s, x) -> (s, p * x)) (0,1)
2269-- $ S.scanl' (\\(s, _) x -> (s + x, x)) (0,1)
2270-- $ S.fromList \[1,2,3,4]
2274-- IMPORTANT: 'scanl'' evaluates the accumulator to WHNF. To avoid building
2275-- lazy expressions inside the accumulator, it is recommended that a strict
2276-- data structure is used for accumulator.
2278-- See also: 'usingStateT'
2281{-# INLINE scanl' #-}
2282scanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
2283scanl' step z m = fromStreamS $ S.scanl' step z $ toStreamS m
2285-- | Like 'scanl'' but does not stream the initial value of the accumulator.
2287-- > postscanl' f z xs = S.drop 1 $ S.scanl' f z xs
2290{-# INLINE postscanl' #-}
2291postscanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
2292postscanl' step z m = fromStreamD $ D.postscanl' step z $ toStreamD m
2294-- XXX this needs to be concurrent
2295-- | Like 'postscanl'' but with a monadic step function and a monadic seed.
2299-- /Since: 0.8.0 (signature change)/
2300{-# INLINE postscanlM' #-}
2301postscanlM' :: (IsStream t, Monad m) => (b -> a -> m b) -> m b -> t m a -> t m b
2302postscanlM' step z m = fromStreamD $ D.postscanlM' step z $ toStreamD m
2304-- XXX prescanl does not sound very useful, enable only if there is a
2305-- compelling use case.
2307-- | Like scanl' but does not stream the final value of the accumulator.
2310{-# INLINE prescanl' #-}
2311prescanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
2312prescanl' step z m = fromStreamD $ D.prescanl' step z $ toStreamD m
2314-- XXX this needs to be concurrent
2315-- | Like prescanl' but with a monadic step function and a monadic seed.
2318{-# INLINE prescanlM' #-}
2319prescanlM' :: (IsStream t, Monad m) => (b -> a -> m b) -> m b -> t m a -> t m b
2320prescanlM' step z m = fromStreamD $ D.prescanlM' step z $ toStreamD m
2322-- XXX this needs to be concurrent
2323-- | Like 'scanl1'' but with a monadic step function.
2326{-# INLINE scanl1M' #-}
2327scanl1M' :: (IsStream t, Monad m) => (a -> a -> m a) -> t m a -> t m a
2328scanl1M' step m = fromStreamD $ D.scanl1M' step $ toStreamD m
2330-- | Like 'scanl'' but for a non-empty stream. The first element of the stream
2331-- is used as the initial value of the accumulator. Does nothing if the stream
2335-- > S.toList $ S.scanl1 (+) $ fromList [1,2,3,4]
2340{-# INLINE scanl1' #-}
2341scanl1' :: (IsStream t, Monad m) => (a -> a -> a) -> t m a -> t m a
2342scanl1' step m = fromStreamD $ D.scanl1' step $ toStreamD m
2344------------------------------------------------------------------------------
2345-- Scanning with a Fold
2346------------------------------------------------------------------------------
2348-- | Scan a stream using the given monadic fold.
2352scan :: (IsStream t, Monad m) => Fold m a b -> t m a -> t m b
2353scan (Fold step begin done) = P.scanlMx' step begin done
2355-- | Postscan a stream using the given monadic fold.
2358{-# INLINE postscan #-}
2359postscan :: (IsStream t, Monad m) => Fold m a b -> t m a -> t m b
2360postscan (Fold step begin done) = P.postscanlMx' step begin done
2362------------------------------------------------------------------------------
2363-- Stateful Transformations
2364------------------------------------------------------------------------------
2366-- XXX this is not a one-to-one map so calling it map may not be right.
2367-- We can perhaps call it zipWithTail or rollWith.
2369-- | Apply a function on every two successive elements of a stream. If the
2370-- stream consists of a single element the output is an empty stream.
2372-- This is the stream equivalent of the list idiom @zipWith f xs (tail xs)@.
2376{-# INLINE rollingMap #-}
2377rollingMap :: (IsStream t, Monad m) => (a -> a -> b) -> t m a -> t m b
2378rollingMap f m = fromStreamD $ D.rollingMap f $ toStreamD m
2380-- | Like 'rollingMap' but with an effectful map function.
2384{-# INLINE rollingMapM #-}
2385rollingMapM :: (IsStream t, Monad m) => (a -> a -> m b) -> t m a -> t m b
2386rollingMapM f m = fromStreamD $ D.rollingMapM f $ toStreamD m
2388------------------------------------------------------------------------------
2389-- Transformation by Filtering
2390------------------------------------------------------------------------------
2392-- | Include only those elements that pass a predicate.
2395{-# INLINE filter #-}
2396#if __GLASGOW_HASKELL__ != 802
2397-- GHC 8.2.2 crashes with this code, when used with "stack"
2398filter :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m a
2399filter p m = fromStreamS $ S.filter p $ toStreamS m
2401filter :: IsStream t => (a -> Bool) -> t m a -> t m a
2405-- | Same as 'filter' but with a monadic predicate.
2408{-# INLINE filterM #-}
2409filterM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
2410filterM p m = fromStreamD $ D.filterM p $ toStreamD m
2412-- | Drop repeated elements that are adjacent to each other.
2416uniq :: (Eq a, IsStream t, Monad m) => t m a -> t m a
2417uniq = fromStreamD . D.uniq . toStreamD
2419-- | Ensures that all the elements of the stream are identical and then returns
2420-- that unique element.
2424the :: (Eq a, Monad m) => SerialT m a -> m (Maybe a)
2425the m = S.the (toStreamS m)
2427-- | Take first 'n' elements from the stream and discard the rest.
2431take :: (IsStream t, Monad m) => Int -> t m a -> t m a
2432take n m = fromStreamS $ S.take n $ toStreamS
2433 (maxYields (Just (fromIntegral n)) m)
2435-- | End the stream as soon as the predicate fails on an element.
2438{-# INLINE takeWhile #-}
2439takeWhile :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m a
2440takeWhile p m = fromStreamS $ S.takeWhile p $ toStreamS m
2442-- | Same as 'takeWhile' but with a monadic predicate.
2445{-# INLINE takeWhileM #-}
2446takeWhileM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
2447takeWhileM p m = fromStreamD $ D.takeWhileM p $ toStreamD m
2449-- | @takeByTime duration@ yields stream elements upto specified time
2450-- @duration@. The duration starts when the stream is evaluated for the first
2451-- time, before the first element is yielded. The time duration is checked
2452-- before generating each element, if the duration has expired the stream
2455-- The total time taken in executing the stream is guaranteed to be /at least/
2456-- @duration@, however, because the duration is checked before generating an
2457-- element, the upper bound is indeterminate and depends on the time taken in
2458-- generating and processing the last element.
2460-- No element is yielded if the duration is zero. At least one element is
2461-- yielded if the duration is non-zero.
2465{-# INLINE takeByTime #-}
2466takeByTime ::(MonadIO m, IsStream t, TimeUnit64 d) => d -> t m a -> t m a
2467takeByTime d = fromStreamD . D.takeByTime d . toStreamD
2469-- | Discard first 'n' elements from the stream and take the rest.
2473drop :: (IsStream t, Monad m) => Int -> t m a -> t m a
2474drop n m = fromStreamS $ S.drop n $ toStreamS m
2476-- | Drop elements in the stream as long as the predicate succeeds and then
2477-- take the rest of the stream.
2480{-# INLINE dropWhile #-}
2481dropWhile :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m a
2482dropWhile p m = fromStreamS $ S.dropWhile p $ toStreamS m
2484-- | Same as 'dropWhile' but with a monadic predicate.
2487{-# INLINE dropWhileM #-}
2488dropWhileM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
2489dropWhileM p m = fromStreamD $ D.dropWhileM p $ toStreamD m
2491-- | @dropByTime duration@ drops stream elements until specified @duration@ has
2492-- passed. The duration begins when the stream is evaluated for the first
2493-- time. The time duration is checked /after/ generating a stream element, the
2494-- element is yielded if the duration has expired otherwise it is dropped.
2496-- The time elapsed before starting to generate the first element is /at most/
2497-- @duration@, however, because the duration expiry is checked after the
2498-- element is generated, the lower bound is indeterminate and depends on the
2499-- time taken in generating an element.
2501-- All elements are yielded if the duration is zero.
2505{-# INLINE dropByTime #-}
2506dropByTime ::(MonadIO m, IsStream t, TimeUnit64 d) => d -> t m a -> t m a
2507dropByTime d = fromStreamD . D.dropByTime d . toStreamD
2509------------------------------------------------------------------------------
2510-- Transformation by Mapping
2511------------------------------------------------------------------------------
2515-- mapM f = sequence . map f
2518-- Apply a monadic function to each element of the stream and replace it with
2519-- the output of the resulting action.
2522-- > drain $ S.mapM putStr $ S.fromList ["a", "b", "c"]
2525-- drain $ S.replicateM 10 (return 1)
2526-- & (serially . S.mapM (\\x -> threadDelay 1000000 >> print x))
2528-- drain $ S.replicateM 10 (return 1)
2529-- & (asyncly . S.mapM (\\x -> threadDelay 1000000 >> print x))
2532-- /Concurrent (do not use with 'parallely' on infinite streams)/
2535{-# INLINE_EARLY mapM #-}
2536mapM :: (IsStream t, MonadAsync m) => (a -> m b) -> t m a -> t m b
2539{-# RULES "mapM serial" mapM = mapMSerial #-}
2540{-# INLINE mapMSerial #-}
2541mapMSerial :: Monad m => (a -> m b) -> SerialT m a -> SerialT m b
2542mapMSerial = Serial.mapM
2546-- sequence = mapM id
2549-- Replace the elements of a stream of monadic actions with the outputs of
2553-- > drain $ S.sequence $ S.fromList [putStr "a", putStr "b", putStrLn "c"]
2556-- drain $ S.replicateM 10 (return $ threadDelay 1000000 >> print 1)
2557-- & (serially . S.sequence)
2559-- drain $ S.replicateM 10 (return $ threadDelay 1000000 >> print 1)
2560-- & (asyncly . S.sequence)
2563-- /Concurrent (do not use with 'parallely' on infinite streams)/
2566{-# INLINE sequence #-}
2567sequence :: (IsStream t, MonadAsync m) => t m (m a) -> t m a
2568sequence m = fromStreamS $ S.sequence (toStreamS m)
2572-- The stateful step function can be simplified to @(s -> a -> m b)@ to provide
2573-- a read-only environment. However, that would just be 'mapM'.
2575-- The initial action could be @m (s, Maybe b)@, and we can also add a final
2576-- action @s -> m (Maybe b)@. This can be used to get pre/post scan like
2577-- functionality and also to flush the state in the end like scanlMAfter'.
2578-- We can also use it along with a fusible version of bracket to get
2579-- scanlMAfter' like functionality. See issue #677.
2581-- This can be further generalized to a type similar to Fold/Parser, giving it
2582-- filtering and parsing capability as well (this is in fact equivalent to
2585-- smapM :: (s -> a -> m (Step s b)) -> m s -> t m a -> t m b
2588-- | A stateful 'mapM', equivalent to a left scan, more like mapAccumL.
2589-- Hopefully, this is a better alternative to @scan@. Separation of state from
2590-- the output makes it easier to think in terms of a shared state, and also
2591-- makes it easier to keep the state fully strict and the output lazy.
2593-- See also: 'scanlM''
2598smapM :: (IsStream t, Monad m) =>
2599 (s -> a -> m (s, b))
2603smapM step initial stream =
2604 -- XXX implement this directly instead of using scanlM'
2605 -- Once we have postscanlM' with monadic initial we can use this code
2606 -- let r = postscanlM'
2607 -- (\(s, _) a -> step s a)
2608 -- (fmap (,undefined) initial)
2612 postscanlM' (\(s, _) a -> step s a) (return (s0, undefined)) stream
2617------------------------------------------------------------------------------
2619------------------------------------------------------------------------------
2621-- | Map a 'Maybe' returning function to a stream, filter out the 'Nothing'
2622-- elements, and return a stream of values extracted from 'Just'.
2627-- mapMaybe f = S.map 'fromJust' . S.filter 'isJust' . S.map f
2631{-# INLINE mapMaybe #-}
2632mapMaybe :: (IsStream t, Monad m) => (a -> Maybe b) -> t m a -> t m b
2633mapMaybe f m = fromStreamS $ S.mapMaybe f $ toStreamS m
2635-- | Like 'mapMaybe' but maps a monadic function.
2640-- mapMaybeM f = S.map 'fromJust' . S.filter 'isJust' . S.mapM f
2643-- /Concurrent (do not use with 'parallely' on infinite streams)/
2646{-# INLINE_EARLY mapMaybeM #-}
2647mapMaybeM :: (IsStream t, MonadAsync m, Functor (t m))
2648 => (a -> m (Maybe b)) -> t m a -> t m b
2649mapMaybeM f = fmap fromJust . filter isJust . K.mapM f
2651{-# RULES "mapMaybeM serial" mapMaybeM = mapMaybeMSerial #-}
2652{-# INLINE mapMaybeMSerial #-}
2653mapMaybeMSerial :: Monad m => (a -> m (Maybe b)) -> SerialT m a -> SerialT m b
2654mapMaybeMSerial f m = fromStreamD $ D.mapMaybeM f $ toStreamD m
2656-- | In a stream of 'Maybe's, discard 'Nothing's and unwrap 'Just's.
2660catMaybes :: (IsStream t, Monad m, Functor (t m)) => t m (Maybe a) -> t m a
2661catMaybes = fmap fromJust . filter isJust
2663------------------------------------------------------------------------------
2664-- Transformation by Reordering
2665------------------------------------------------------------------------------
2667-- XXX Use a compact region list to temporarily store the list, in both reverse
2668-- as well as in reverse'.
2670-- /Note:/ 'reverse'' is much faster than this, use that when performance
2673-- > reverse = S.foldlT (flip S.cons) S.nil
2675-- | Returns the elements of the stream in reverse order. The stream must be
2676-- finite. Note that this necessarily buffers the entire stream in memory.
2678-- /Since 0.7.0 (Monad m constraint)/
2681{-# INLINE reverse #-}
2682reverse :: (IsStream t, Monad m) => t m a -> t m a
2683reverse s = fromStreamS $ S.reverse $ toStreamS s
2685-- | Like 'reverse' but several times faster, requires a 'Storable' instance.
2688{-# INLINE reverse' #-}
2689reverse' :: (IsStream t, MonadIO m, Storable a) => t m a -> t m a
2690reverse' s = fromStreamD $ D.reverse' $ toStreamD s
2692------------------------------------------------------------------------------
2693-- Transformation by Inserting
2694------------------------------------------------------------------------------
2696-- intersperseM = intersperseBySpan 1
2698-- | Insert an effect and its output before consuming an element of a stream
2699-- except the first one.
2702-- >>> S.toList $ S.trace putChar $ S.intersperseM (putChar '.' >> return ',') $ S.fromList "hello"
2703-- > h.,e.,l.,l.,o"h,e,l,l,o"
2707{-# INLINE intersperseM #-}
2708intersperseM :: (IsStream t, MonadAsync m) => m a -> t m a -> t m a
2709intersperseM m = fromStreamS . S.intersperseM m . toStreamS
2711-- | Insert a side effect before consuming an element of a stream except the
2715-- >>> S.drain $ S.trace putChar $ S.intersperseM_ (putChar '.') $ S.fromList "hello"
2720{-# INLINE intersperseM_ #-}
2721intersperseM_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
2722intersperseM_ m = fromStreamD . D.intersperseM_ m . toStreamD
2724-- | Insert a pure value between successive elements of a stream.
2727-- > S.toList $ S.intersperse ',' $ S.fromList "hello"
2732{-# INLINE intersperse #-}
2733intersperse :: (IsStream t, MonadAsync m) => a -> t m a -> t m a
2734intersperse a = fromStreamS . S.intersperse a . toStreamS
2736-- | Insert an effect and its output after consuming an element of a stream.
2739-- >>> S.toList $ S.trace putChar $ S.intersperseSuffix (putChar '.' >> return ',') $ S.fromList "hello"
2740-- > h.,e.,l.,l.,o.,"h,e,l,l,o,"
2744{-# INLINE intersperseSuffix #-}
2745intersperseSuffix :: (IsStream t, MonadAsync m) => m a -> t m a -> t m a
2746intersperseSuffix m = fromStreamD . D.intersperseSuffix m . toStreamD
2748-- | Insert a side effect after consuming an element of a stream.
2751-- > S.mapM_ putChar $ S.intersperseSuffix_ (threadDelay 1000000) $ S.fromList "hello"
2756{-# INLINE intersperseSuffix_ #-}
2757intersperseSuffix_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
2758intersperseSuffix_ m = fromStreamD . D.intersperseSuffix_ m . toStreamD
2760-- | Insert a side effect before consuming an element of a stream.
2763-- >>> S.toList $ S.trace putChar $ S.interspersePrefix_ (putChar '.' >> return ',') $ S.fromList "hello"
2764-- > .h.e.l.l.o"hello"
2767-- See also: 'trace_'
2773{-# INLINE interspersePrefix_ #-}
2774interspersePrefix_ :: (IsStream t, MonadAsync m) => m b -> t m a -> t m a
2775interspersePrefix_ m = mapM (\x -> void m >> return x)
2777-- Note: delay must be serial.
2779-- | Introduce a delay of specified seconds before consuming an element of the
2780-- stream except the first one.
2783-- >>> S.mapM_ print $ S.timestamped $ S.delay 1 $ S.enumerateFromTo 1 3
2784-- > (AbsTime (TimeSpec {sec = 2502706, nsec = 751137000}),1)
2785-- > (AbsTime (TimeSpec {sec = 2502707, nsec = 743535000}),2)
2786-- > (AbsTime (TimeSpec {sec = 2502708, nsec = 749758000}),3)
2792delay :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
2793delay n = intersperseM_ $ liftIO $ threadDelay $ round $ n * 1000000
2795-- Note: delay must be serial.
2797-- | Introduce a delay of specified seconds after consuming an element of a
2801-- >>> S.mapM_ print $ S.timestamped $ S.delayPost 1 $ S.enumerateFromTo 1 3
2802-- > (AbsTime (TimeSpec {sec = 2502826, nsec = 119030000}),1)
2803-- > (AbsTime (TimeSpec {sec = 2502827, nsec = 111393000}),2)
2804-- > (AbsTime (TimeSpec {sec = 2502828, nsec = 112221000}),3)
2809{-# INLINE delayPost #-}
2810delayPost :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
2811delayPost n = intersperseSuffix_ $ liftIO $ threadDelay $ round $ n * 1000000
2813-- Note: delay must be serial, that's why 'trace_' is used.
2815-- | Introduce a delay of specified seconds before consuming an element of a
2819-- >>> S.mapM_ print $ S.timestamped $ S.delayPre 1 $ S.enumerateFromTo 1 3
2820-- > (AbsTime (TimeSpec {sec = 2502207, nsec = 533177000}),1)
2821-- > (AbsTime (TimeSpec {sec = 2502208, nsec = 530859000}),2)
2822-- > (AbsTime (TimeSpec {sec = 2502209, nsec = 531619000}),3)
2827{-# INLINE delayPre #-}
2828delayPre :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
2829delayPre n = trace_ $ liftIO $ threadDelay $ round $ n * 1000000
2831-- | Like 'intersperseSuffix' but intersperses an effectful action into the
2832-- input stream after every @n@ elements and after the last element.
2835-- > S.toList $ S.intersperseSuffixBySpan 2 (return ',') $ S.fromList "hello"
2841{-# INLINE intersperseSuffixBySpan #-}
2842intersperseSuffixBySpan :: (IsStream t, MonadAsync m)
2843 => Int -> m a -> t m a -> t m a
2844intersperseSuffixBySpan n eff =
2845 fromStreamD . D.intersperseSuffixBySpan n eff . toStreamD
2848-- | Intersperse a monadic action into the input stream after every @n@
2852-- > S.toList $ S.intersperseBySpan 2 (return ',') $ S.fromList "hello"
2857{-# INLINE intersperseBySpan #-}
2858intersperseBySpan :: IsStream t => Int -> m a -> t m a -> t m a
2859intersperseBySpan _n _f _xs = undefined
2862-- | Intersperse a monadic action into the input stream after every @n@
2866-- > S.drain $ S.interjectSuffix 1 (putChar ',') $ S.mapM (\\x -> threadDelay 1000000 >> putChar x) $ S.fromList "hello"
2871{-# INLINE interjectSuffix #-}
2873 :: (IsStream t, MonadAsync m)
2874 => Double -> m a -> t m a -> t m a
2875interjectSuffix n f xs = xs `Par.parallelFst` repeatM timed
2876 where timed = liftIO (threadDelay (round $ n * 1000000)) >> f
2878-- | @insertBy cmp elem stream@ inserts @elem@ before the first element in
2879-- @stream@ that is less than @elem@ when compared using @cmp@.
2882-- insertBy cmp x = 'mergeBy' cmp ('yield' x)
2886-- > S.toList $ S.insertBy compare 2 $ S.fromList [1,3,5]
2891{-# INLINE insertBy #-}
2893 (IsStream t, Monad m) => (a -> a -> Ordering) -> a -> t m a -> t m a
2894insertBy cmp x m = fromStreamS $ S.insertBy cmp x (toStreamS m)
2896------------------------------------------------------------------------------
2898------------------------------------------------------------------------------
2900-- | Deletes the first occurrence of the element in the stream that satisfies
2901-- the given equality predicate.
2904-- > S.toList $ S.deleteBy (==) 3 $ S.fromList [1,3,3,5]
2909{-# INLINE deleteBy #-}
2910deleteBy :: (IsStream t, Monad m) => (a -> a -> Bool) -> a -> t m a -> t m a
2911deleteBy cmp x m = fromStreamS $ S.deleteBy cmp x (toStreamS m)
2913------------------------------------------------------------------------------
2915------------------------------------------------------------------------------
2918-- > indexed = S.postscanl' (\(i, _) x -> (i + 1, x)) (-1,undefined)
2919-- > indexed = S.zipWith (,) (S.enumerateFrom 0)
2921-- Pair each element in a stream with its index, starting from index 0.
2924-- > S.toList $ S.indexed $ S.fromList "hello"
2925-- [(0,'h'),(1,'e'),(2,'l'),(3,'l'),(4,'o')]
2929{-# INLINE indexed #-}
2930indexed :: (IsStream t, Monad m) => t m a -> t m (Int, a)
2931indexed = fromStreamD . D.indexed . toStreamD
2934-- > indexedR n = S.postscanl' (\(i, _) x -> (i - 1, x)) (n + 1,undefined)
2935-- > indexedR n = S.zipWith (,) (S.enumerateFromThen n (n - 1))
2937-- Pair each element in a stream with its index, starting from the
2938-- given index @n@ and counting down.
2941-- > S.toList $ S.indexedR 10 $ S.fromList "hello"
2942-- [(10,'h'),(9,'e'),(8,'l'),(7,'l'),(6,'o')]
2946{-# INLINE indexedR #-}
2947indexedR :: (IsStream t, Monad m) => Int -> t m a -> t m (Int, a)
2948indexedR n = fromStreamD . D.indexedR n . toStreamD
2950-- Note: The timestamp stream must be the second stream in the zip so that the
2951-- timestamp is generated after generating the stream element and not before.
2952-- If we do not do that then the following example will generate the same
2953-- timestamp for first two elements:
2955-- S.mapM_ print $ S.timestamped $ S.delay $ S.enumerateFromTo 1 3
2957-- | Pair each element in a stream with an absolute timestamp, using a clock of
2958-- specified granularity. The timestamp is generated just before the element
2962-- >>> S.mapM_ print $ S.timestampWith 0.01 $ S.delay 1 $ S.enumerateFromTo 1 3
2967{-# INLINE timestampWith #-}
2968timestampWith :: (IsStream t, MonadAsync m, Functor (t m))
2969 => Double -> t m a -> t m (AbsTime, a)
2970timestampWith g stream = Z.zipWith (flip (,)) stream (absTimesWith g)
2972-- TBD: check performance vs a custom implementation without using zipWith.
2974-- | Pair each element in a stream with an absolute timestamp, using a clock of
2975-- 10 ms granularity. The timestamp is generated just before the element is
2979-- >>> S.mapM_ print $ S.timestamped $ S.delay 1 $ S.enumerateFromTo 1 3
2980-- (AbsTime (TimeSpec {sec = 2460689, nsec = 641121000}),1)
2981-- (AbsTime (TimeSpec {sec = 2460690, nsec = 639334000}),2)
2982-- (AbsTime (TimeSpec {sec = 2460691, nsec = 644479000}),3)
2987{-# INLINE timestamped #-}
2988timestamped :: (IsStream t, MonadAsync m, Functor (t m))
2989 => t m a -> t m (AbsTime, a)
2990timestamped = timestampWith 0.01
2992-- | Pair each element in a stream with relative times starting from 0, using a
2993-- clock with the specified granularity. The time is measured just before the
2994-- element is consumed.
2997-- >>> S.mapM_ print $ S.timeIndexWith 0.01 $ S.delay 1 $ S.enumerateFromTo 1 3
3002{-# INLINE timeIndexWith #-}
3003timeIndexWith :: (IsStream t, MonadAsync m, Functor (t m))
3004 => Double -> t m a -> t m (RelTime64, a)
3005timeIndexWith g stream = Z.zipWith (flip (,)) stream (relTimesWith g)
3007-- | Pair each element in a stream with relative times starting from 0, using a
3008-- 10 ms granularity clock. The time is measured just before the element is
3012-- >>> S.mapM_ print $ S.timeIndexed $ S.delay 1 $ S.enumerateFromTo 1 3
3013-- (RelTime64 (NanoSecond64 0),1)
3014-- (RelTime64 (NanoSecond64 996239000),2)
3015-- (RelTime64 (NanoSecond64 1996712000),3)
3020{-# INLINE timeIndexed #-}
3021timeIndexed :: (IsStream t, MonadAsync m, Functor (t m))
3022 => t m a -> t m (RelTime64, a)
3023timeIndexed = timeIndexWith 0.01
3025------------------------------------------------------------------------------
3027------------------------------------------------------------------------------
3029-- | Compare two streams for equality using an equality function.
3032{-# INLINABLE eqBy #-}
3033eqBy :: (IsStream t, Monad m) => (a -> b -> Bool) -> t m a -> t m b -> m Bool
3036-- | Compare two streams lexicographically using a comparison function.
3039{-# INLINABLE cmpBy #-}
3041 :: (IsStream t, Monad m)
3042 => (a -> b -> Ordering) -> t m a -> t m b -> m Ordering
3045------------------------------------------------------------------------------
3047------------------------------------------------------------------------------
3049-- | Merge two streams using a comparison function. The head elements of both
3050-- the streams are compared and the smaller of the two elements is emitted, if
3051-- both elements are equal then the element from the first stream is used
3054-- If the streams are sorted in ascending order, the resulting stream would
3055-- also remain sorted in ascending order.
3058-- > S.toList $ S.mergeBy compare (S.fromList [1,3,5]) (S.fromList [2,4,6,8])
3063{-# INLINABLE mergeBy #-}
3065 (IsStream t, Monad m) => (a -> a -> Ordering) -> t m a -> t m a -> t m a
3066mergeBy f m1 m2 = fromStreamS $ S.mergeBy f (toStreamS m1) (toStreamS m2)
3068-- | Like 'mergeBy' but with a monadic comparison function.
3070-- Merge two streams randomly:
3073-- > randomly _ _ = randomIO >>= \x -> return $ if x then LT else GT
3074-- > S.toList $ S.mergeByM randomly (S.fromList [1,1,1,1]) (S.fromList [2,2,2,2])
3078-- Merge two streams in a proportion of 2:1:
3081-- proportionately m n = do
3082-- ref <- newIORef $ cycle $ concat [replicate m LT, replicate n GT]
3083-- return $ \\_ _ -> do
3084-- r <- readIORef ref
3085-- writeIORef ref $ tail r
3089-- f <- proportionately 2 1
3090-- xs <- S.toList $ S.mergeByM f (S.fromList [1,1,1,1,1,1]) (S.fromList [2,2,2])
3094-- [1,1,2,1,1,2,1,1,2]
3098{-# INLINABLE mergeByM #-}
3100 :: (IsStream t, Monad m)
3101 => (a -> a -> m Ordering) -> t m a -> t m a -> t m a
3102mergeByM f m1 m2 = fromStreamS $ S.mergeByM f (toStreamS m1) (toStreamS m2)
3105-- | Like 'mergeByM' but stops merging as soon as any of the two streams stops.
3106{-# INLINABLE mergeEndByAny #-}
3108 :: (IsStream t, Monad m)
3109 => (a -> a -> m Ordering) -> t m a -> t m a -> t m a
3110mergeEndByAny f m1 m2 = fromStreamD $
3111 D.mergeEndByAny f (toStreamD m1) (toStreamD m2)
3113-- Like 'mergeByM' but stops merging as soon as the first stream stops.
3114{-# INLINABLE mergeEndByFirst #-}
3116 :: (IsStream t, Monad m)
3117 => (a -> a -> m Ordering) -> t m a -> t m a -> t m a
3118mergeEndByFirst f m1 m2 = fromStreamS $
3119 D.mergeEndByFirst f (toStreamD m1) (toStreamD m2)
3122-- Holding this back for now, we may want to use the name "merge" differently
3124-- | Same as @'mergeBy' 'compare'@.
3127-- > S.toList $ S.merge (S.fromList [1,3,5]) (S.fromList [2,4,6,8])
3132{-# INLINABLE merge #-}
3134 (IsStream t, Monad m, Ord a) => t m a -> t m a -> t m a
3135merge = mergeBy compare
3138-- | Like 'mergeBy' but merges concurrently (i.e. both the elements being
3139-- merged are generated concurrently).
3142{-# INLINE mergeAsyncBy #-}
3143mergeAsyncBy :: (IsStream t, MonadAsync m)
3144 => (a -> a -> Ordering) -> t m a -> t m a -> t m a
3145mergeAsyncBy f = mergeAsyncByM (\a b -> return $ f a b)
3147-- | Like 'mergeByM' but merges concurrently (i.e. both the elements being
3148-- merged are generated concurrently).
3151{-# INLINE mergeAsyncByM #-}
3152mergeAsyncByM :: (IsStream t, MonadAsync m)
3153 => (a -> a -> m Ordering) -> t m a -> t m a -> t m a
3154mergeAsyncByM f m1 m2 = fromStreamD $
3155 D.mergeByM f (D.mkParallelD $ toStreamD m1) (D.mkParallelD $ toStreamD m2)
3157------------------------------------------------------------------------------
3159------------------------------------------------------------------------------
3161-- | @concatMapWith merge map stream@ is a two dimensional looping combinator.
3162-- The first argument specifies a merge or concat function that is used to
3163-- merge the streams generated by applying the second argument i.e. the @map@
3164-- function to each element of the input stream. The concat function could be
3165-- 'serial', 'parallel', 'async', 'ahead' or any other zip or merge function
3166-- and the second argument could be any stream generation function using a
3169-- /Compare 'foldMapWith'/
3172{-# INLINE concatMapWith #-}
3175 => (t m b -> t m b -> t m b)
3179concatMapWith = K.concatMapBy
3181-- | Like 'concatMapWith' but carries a state which can be used to share
3182-- information across multiple steps of concat.
3185-- concatSmapMWith combine f initial = concatMapWith combine id . smapM f initial
3190{-# INLINE concatSmapMWith #-}
3192 :: (IsStream t, Monad m)
3193 => (t m b -> t m b -> t m b)
3194 -> (s -> a -> m (s, t m b))
3198concatSmapMWith combine f initial = concatMapWith combine id . smapM f initial
3200-- | Map a stream producing function on each element of the stream and then
3201-- flatten the results into a single stream.
3204-- concatMap f = 'concat . map f'
3205-- concatMap = 'concatMapWith' 'Serial.serial'
3206-- concatMap f = 'concatMapM' (return . f)
3207-- concatMap f = 'concatUnfold' (UF.lmap f UF.fromStream)
3211{-# INLINE concatMap #-}
3212concatMap ::(IsStream t, Monad m) => (a -> t m b) -> t m a -> t m b
3213concatMap f m = fromStreamD $ D.concatMap (toStreamD . f) (toStreamD m)
3215-- | Flatten a stream of streams to a single stream.
3218-- concat = concatMap id
3222{-# INLINE concat #-}
3223concat :: (IsStream t, Monad m) => t m (t m a) -> t m a
3224concat = concatMap id
3226-- | Append the outputs of two streams, yielding all the elements from the
3227-- first stream and then yielding all the elements from the second stream.
3229-- IMPORTANT NOTE: This could be 100x faster than @serial/<>@ for appending a
3230-- few (say 100) streams because it can fuse via stream fusion. However, it
3231-- does not scale for a large number of streams (say 1000s) and becomes
3232-- qudartically slow. Therefore use this for custom appending of a few streams
3233-- but use 'concatMap' or 'concatMapWith serial' for appending @n@ streams or
3234-- infinite containers of streams.
3237{-# INLINE append #-}
3238append ::(IsStream t, Monad m) => t m b -> t m b -> t m b
3239append m1 m2 = fromStreamD $ D.append (toStreamD m1) (toStreamD m2)
3241-- XXX Same as 'wSerial'. We should perhaps rename wSerial to interleave.
3242-- XXX Document the interleaving behavior of side effects in all the
3243-- interleaving combinators.
3244-- XXX Write time-domain equivalents of these. In the time domain we can
3245-- interleave two streams such that the value of second stream is always taken
3246-- from its last value even if no new value is being yielded, like
3247-- zipWithLatest. It would be something like interleaveWithLatest.
3249-- | Interleaves the outputs of two streams, yielding elements from each stream
3250-- alternately, starting from the first stream. If any of the streams finishes
3251-- early the other stream continues alone until it too finishes.
3253-- >>> :set -XOverloadedStrings
3254-- >>> interleave "ab" ",,,," :: SerialT Identity Char
3256-- >>> interleave "abcd" ",," :: SerialT Identity Char
3259-- 'interleave' is dual to 'interleaveMin', it can be called @interleaveMax@.
3261-- Do not use at scale in concatMapWith.
3264{-# INLINE interleave #-}
3265interleave ::(IsStream t, Monad m) => t m b -> t m b -> t m b
3266interleave m1 m2 = fromStreamD $ D.interleave (toStreamD m1) (toStreamD m2)
3268-- | Interleaves the outputs of two streams, yielding elements from each stream
3269-- alternately, starting from the first stream. As soon as the first stream
3270-- finishes, the output stops, discarding the remaining part of the second
3271-- stream. In this case, the last element in the resulting stream would be from
3272-- the second stream. If the second stream finishes early then the first stream
3273-- still continues to yield elements until it finishes.
3275-- >>> :set -XOverloadedStrings
3276-- >>> interleaveSuffix "abc" ",,,," :: SerialT Identity Char
3278-- >>> interleaveSuffix "abc" "," :: SerialT Identity Char
3281-- 'interleaveSuffix' is a dual of 'interleaveInfix'.
3283-- Do not use at scale in concatMapWith.
3286{-# INLINE interleaveSuffix #-}
3287interleaveSuffix ::(IsStream t, Monad m) => t m b -> t m b -> t m b
3288interleaveSuffix m1 m2 =
3289 fromStreamD $ D.interleaveSuffix (toStreamD m1) (toStreamD m2)
3291-- | Interleaves the outputs of two streams, yielding elements from each stream
3292-- alternately, starting from the first stream and ending at the first stream.
3293-- If the second stream is longer than the first, elements from the second
3294-- stream are infixed with elements from the first stream. If the first stream
3295-- is longer then it continues yielding elements even after the second stream
3298-- >>> :set -XOverloadedStrings
3299-- >>> interleaveInfix "abc" ",,,," :: SerialT Identity Char
3301-- >>> interleaveInfix "abc" "," :: SerialT Identity Char
3304-- 'interleaveInfix' is a dual of 'interleaveSuffix'.
3306-- Do not use at scale in concatMapWith.
3309{-# INLINE interleaveInfix #-}
3310interleaveInfix ::(IsStream t, Monad m) => t m b -> t m b -> t m b
3311interleaveInfix m1 m2 =
3312 fromStreamD $ D.interleaveInfix (toStreamD m1) (toStreamD m2)
3314-- | Interleaves the outputs of two streams, yielding elements from each stream
3315-- alternately, starting from the first stream. The output stops as soon as any
3316-- of the two streams finishes, discarding the remaining part of the other
3317-- stream. The last element of the resulting stream would be from the longer
3320-- >>> :set -XOverloadedStrings
3321-- >>> interleaveMin "ab" ",,,," :: SerialT Identity Char
3323-- >>> interleaveMin "abcd" ",," :: SerialT Identity Char
3326-- 'interleaveMin' is dual to 'interleave'.
3328-- Do not use at scale in concatMapWith.
3331{-# INLINE interleaveMin #-}
3332interleaveMin ::(IsStream t, Monad m) => t m b -> t m b -> t m b
3333interleaveMin m1 m2 = fromStreamD $ D.interleaveMin (toStreamD m1) (toStreamD m2)
3335-- | Schedule the execution of two streams in a fair round-robin manner,
3336-- executing each stream once, alternately. Execution of a stream may not
3337-- necessarily result in an output, a stream may chose to @Skip@ producing an
3338-- element until later giving the other stream a chance to run. Therefore, this
3339-- combinator fairly interleaves the execution of two streams rather than
3340-- fairly interleaving the output of the two streams. This can be useful in
3341-- co-operative multitasking without using explicit threads. This can be used
3342-- as an alternative to `async`.
3344-- Do not use at scale in concatMapWith.
3347{-# INLINE roundrobin #-}
3348roundrobin ::(IsStream t, Monad m) => t m b -> t m b -> t m b
3349roundrobin m1 m2 = fromStreamD $ D.roundRobin (toStreamD m1) (toStreamD m2)
3351-- | Map a stream producing monadic function on each element of the stream
3352-- and then flatten the results into a single stream. Since the stream
3353-- generation function is monadic, unlike 'concatMap', it can produce an
3354-- effect at the beginning of each iteration of the inner loop.
3357{-# INLINE concatMapM #-}
3358concatMapM :: (IsStream t, Monad m) => (a -> m (t m b)) -> t m a -> t m b
3359concatMapM f m = fromStreamD $ D.concatMapM (fmap toStreamD . f) (toStreamD m)
3361-- | Given a stream value in the underlying monad, lift and join the underlying
3362-- monad with the stream monad.
3365-- concatM = concat . yieldM
3366-- concatM = concat . lift -- requires @(MonadTrans t)@
3367-- concatM = join . lift -- requires @(MonadTrans t@, @Monad (t m))@
3370-- See also: 'concat', 'sequence'
3374{-# INLINE concatM #-}
3375concatM :: (IsStream t, Monad m) => m (t m a) -> t m a
3376concatM generator = concatMapM (\() -> generator) (yield ())
3378-- | Like 'concatMap' but uses an 'Unfold' for stream generation. Unlike
3379-- 'concatMap' this can fuse the 'Unfold' code with the inner loop and
3380-- therefore provide many times better performance.
3383{-# INLINE concatUnfold #-}
3384concatUnfold ::(IsStream t, Monad m) => Unfold m a b -> t m a -> t m b
3385concatUnfold u m = fromStreamD $ D.concatMapU u (toStreamD m)
3387-- | Like 'concatUnfold' but interleaves the streams in the same way as
3388-- 'interleave' behaves instead of appending them.
3391{-# INLINE concatUnfoldInterleave #-}
3392concatUnfoldInterleave ::(IsStream t, Monad m)
3393 => Unfold m a b -> t m a -> t m b
3394concatUnfoldInterleave u m =
3395 fromStreamD $ D.concatUnfoldInterleave u (toStreamD m)
3397-- | Like 'concatUnfold' but executes the streams in the same way as
3401{-# INLINE concatUnfoldRoundrobin #-}
3402concatUnfoldRoundrobin ::(IsStream t, Monad m)
3403 => Unfold m a b -> t m a -> t m b
3404concatUnfoldRoundrobin u m =
3405 fromStreamD $ D.concatUnfoldRoundrobin u (toStreamD m)
3407-- XXX we can swap the order of arguments to gintercalate so that the
3408-- definition of concatUnfold becomes simpler? The first stream should be
3409-- infixed inside the second one. However, if we change the order in
3410-- "interleave" as well similarly, then that will make it a bit unintuitive.
3412-- > concatUnfold unf str =
3413-- > gintercalate unf str (UF.nilM (\_ -> return ())) (repeat ())
3415-- | 'interleaveInfix' followed by unfold and concat.
3418{-# INLINE gintercalate #-}
3420 :: (IsStream t, Monad m)
3421 => Unfold m a c -> t m a -> Unfold m b c -> t m b -> t m c
3422gintercalate unf1 str1 unf2 str2 =
3423 D.fromStreamD $ D.gintercalate
3424 unf1 (D.toStreamD str1)
3425 unf2 (D.toStreamD str2)
3427-- XXX The order of arguments in "intercalate" is consistent with the list
3428-- intercalate but inconsistent with gintercalate and other stream interleaving
3429-- combinators. We can change the order of the arguments in other combinators
3430-- but then 'interleave' combinator may become a bit unintuitive because we
3431-- will be starting with the second stream.
3433-- > intercalate seed unf str = gintercalate unf str unf (repeatM seed)
3434-- > intercalate a unf str = concatUnfold unf $ intersperse a str
3436-- | 'intersperse' followed by unfold and concat.
3438-- > unwords = intercalate " " UF.fromList
3440-- >>> intercalate " " UF.fromList ["abc", "def", "ghi"]
3444{-# INLINE intercalate #-}
3445intercalate :: (IsStream t, Monad m)
3446 => b -> Unfold m b c -> t m b -> t m c
3447intercalate seed unf str = D.fromStreamD $
3448 D.concatMapU unf $ D.intersperse seed (toStreamD str)
3450-- > interpose x unf str = gintercalate unf str UF.identity (repeat x)
3452-- | Unfold the elements of a stream, intersperse the given element between the
3453-- unfolded streams and then concat them into a single stream.
3455-- > unwords = S.interpose ' '
3458{-# INLINE interpose #-}
3459interpose :: (IsStream t, Monad m)
3460 => c -> Unfold m b c -> t m b -> t m c
3461interpose x unf str =
3462 D.fromStreamD $ D.interpose (return x) unf (D.toStreamD str)
3464-- | 'interleaveSuffix' followed by unfold and concat.
3467{-# INLINE gintercalateSuffix #-}
3469 :: (IsStream t, Monad m)
3470 => Unfold m a c -> t m a -> Unfold m b c -> t m b -> t m c
3471gintercalateSuffix unf1 str1 unf2 str2 =
3472 D.fromStreamD $ D.gintercalateSuffix
3473 unf1 (D.toStreamD str1)
3474 unf2 (D.toStreamD str2)
3476-- > intercalateSuffix seed unf str = gintercalateSuffix unf str unf (repeatM seed)
3477-- > intercalateSuffix a unf str = concatUnfold unf $ intersperseSuffix a str
3479-- | 'intersperseSuffix' followed by unfold and concat.
3481-- > unlines = intercalateSuffix "\n" UF.fromList
3483-- >>> intercalate "\n" UF.fromList ["abc", "def", "ghi"]
3484-- > "abc\ndef\nghi\n"
3487{-# INLINE intercalateSuffix #-}
3488intercalateSuffix :: (IsStream t, Monad m)
3489 => b -> Unfold m b c -> t m b -> t m c
3490intercalateSuffix seed unf str = fromStreamD $ D.concatMapU unf
3491 $ D.intersperseSuffix (return seed) (D.toStreamD str)
3493-- interposeSuffix x unf str = gintercalateSuffix unf str UF.identity (repeat x)
3495-- | Unfold the elements of a stream, append the given element after each
3496-- unfolded stream and then concat them into a single stream.
3498-- > unlines = S.interposeSuffix '\n'
3501{-# INLINE interposeSuffix #-}
3502interposeSuffix :: (IsStream t, Monad m)
3503 => c -> Unfold m b c -> t m b -> t m c
3504interposeSuffix x unf str =
3505 D.fromStreamD $ D.interposeSuffix (return x) unf (D.toStreamD str)
3507------------------------------------------------------------------------------
3509------------------------------------------------------------------------------
3511-- | Like 'iterateM' but iterates after mapping a stream generator on the
3514-- Yield an input element in the output stream, map a stream generator on it
3515-- and then do the same on the resulting stream. This can be used for a depth
3516-- first traversal of a tree like structure.
3518-- Note that 'iterateM' is a special case of 'iterateMapWith':
3521-- iterateM f = iterateMapWith serial (yieldM . f) . yieldM
3524-- It can be used to traverse a tree structure. For example, to list a
3528-- Stream.iterateMapWith Stream.serial
3529-- (either Dir.toEither (const nil))
3530-- (yield (Left "tmp"))
3535{-# INLINE iterateMapWith #-}
3538 => (t m a -> t m a -> t m a)
3542iterateMapWith combine f = concatMapWith combine go
3544 go x = yield x `combine` concatMapWith combine go (f x)
3547{-# INLINE iterateUnfold #-}
3548iterateUnfold :: (IsStream t, MonadAsync m)
3549 => Unfold m a a -> t m a -> t m a
3550iterateUnfold unf xs = undefined
3553------------------------------------------------------------------------------
3555------------------------------------------------------------------------------
3557-- To traverse graphs we need a state to be carried around in the traversal.
3558-- For example, we can use a hashmap to store the visited status of nodes.
3560-- | Like 'iterateMap' but carries a state in the stream generation function.
3561-- This can be used to traverse graph like structures, we can remember the
3562-- visited nodes in the state to avoid cycles.
3564-- Note that a combination of 'iterateMap' and 'usingState' can also be used to
3565-- traverse graphs. However, this function provides a more localized state
3566-- instead of using a global state.
3572{-# INLINE iterateSmapMWith #-}
3574 :: (IsStream t, Monad m)
3575 => (t m a -> t m a -> t m a)
3576 -> (b -> a -> m (b, t m a))
3580iterateSmapMWith combine f initial stream =
3581 concatMap (\b -> concatMapWith combine (go b) stream) (yieldM initial)
3585 go b a = yield a `combine` feedback b a
3589 (\(b1, s) -> concatMapWith combine (go b1) s)
3592------------------------------------------------------------------------------
3594------------------------------------------------------------------------------
3596-- | Discard 'Right's and unwrap 'Left's in an 'Either' stream.
3600lefts :: (IsStream t, Monad m, Functor (t m)) => t m (Either a b) -> t m a
3601lefts = fmap (fromLeft undefined) . filter isLeft
3603-- | Discard 'Left's and unwrap 'Right's in an 'Either' stream.
3607rights :: (IsStream t, Monad m, Functor (t m)) => t m (Either a b) -> t m b
3608rights = fmap (fromRight undefined) . filter isRight
3610-- | In an 'Either' stream iterate on 'Left's. This is a special case of
3614-- iterateMapLeftsWith combine f = iterateMapWith combine (either f (const nil))
3617-- To traverse a directory tree:
3620-- iterateMapLeftsWith serial Dir.toEither (yield (Left "tmp"))
3625{-# INLINE iterateMapLeftsWith #-}
3628 => (t m (Either a b) -> t m (Either a b) -> t m (Either a b))
3629 -> (a -> t m (Either a b))
3632iterateMapLeftsWith combine f = iterateMapWith combine (either f (const K.nil))
3634------------------------------------------------------------------------------
3636------------------------------------------------------------------------------
3638-- Splitting operations that take a predicate and a Fold can be
3639-- expressed using parseMany. Operations like chunksOf, intervalsOf, split*,
3640-- can be expressed using parseMany when used with an appropriate Parser.
3642-- XXX We need takeGE/takeBetween to implement "some" using "many".
3644-- | Apply a 'Parser' repeatedly on a stream and emit the parsed values in the
3647-- This is the streaming equivalent of the 'Streamly.Internal.Data.Parser.many'
3650-- >>> S.toList $ S.parseMany (PR.take 2 $ PR.fromFold FL.sum) $ S.fromList [1..10]
3653-- >>> S.toList $ S.parseMany (PR.line FL.toList) $ S.fromList "hello\nworld"
3654-- > ["hello\n","world"]
3658{-# INLINE parseMany #-}
3660 :: (IsStream t, MonadThrow m)
3665 D.fromStreamD $ D.parseMany (PRK.fromParserK p) (D.toStreamD m)
3667{-# INLINE parseManyD #-}
3669 :: (IsStream t, MonadThrow m)
3674 D.fromStreamD $ D.parseMany p (D.toStreamD m)
3676-- | @parseManyTill collect test stream@ tries the parser @test@ on the input,
3677-- if @test@ fails it backtracks and tries @collect@, after @collect@ succeeds
3678-- @test@ is tried again and so on. The parser stops when @test@ succeeds. The
3679-- output of @test@ is discarded and the output of @collect@ is emitted in the
3680-- output stream. The parser fails if @collect@ fails.
3684{-# INLINE parseManyTill #-}
3686 -- (IsStream t, MonadThrow m) =>
3691parseManyTill = undefined
3693-- | Iterate a parser generating function on a stream. The initial value @b@ is
3694-- used to generate the first parser, the parser is applied on the stream and
3695-- the result is used to generate the next parser and so on.
3697-- >>> S.toList $ S.map getSum $ S.parseIterate (\b -> PR.take 2 (FL.mconcatTo b)) 0 $ S.map Sum $ S.fromList [1..10]
3698-- > [3,10,21,36,55,55]
3700-- This is the streaming equivalent of monad like sequenced application of
3701-- parsers where next parser is dependent on the previous parser.
3705{-# INLINE parseIterate #-}
3707 :: (IsStream t, MonadThrow m)
3708 => (b -> Parser m a b)
3712parseIterate f i m = D.fromStreamD $
3713 D.parseIterate (PRK.fromParserK . f) i (D.toStreamD m)
3715------------------------------------------------------------------------------
3716-- Grouping/Splitting
3717------------------------------------------------------------------------------
3719------------------------------------------------------------------------------
3720-- Grouping without looking at elements
3721------------------------------------------------------------------------------
3723------------------------------------------------------------------------------
3725------------------------------------------------------------------------------
3728------------------------------------------------------------------------------
3730------------------------------------------------------------------------------
3732------------------------------------------------------------------------------
3733-- Generalized grouping
3734------------------------------------------------------------------------------
3736-- This combinator is the most general grouping combinator and can be used to
3737-- implement all other grouping combinators.
3739-- XXX check if this can implement the splitOn combinator i.e. we can slide in
3740-- new elements, slide out old elements and incrementally compute the hash.
3741-- Also, can we implement the windowed classification combinators using this?
3743-- In fact this is a parse. Instead of using a special return value in the fold
3744-- we are using a mapping function.
3746-- Note that 'scanl'' (usually followed by a map to extract the desired value
3747-- from the accumulator) can be used to realize many implementations e.g. a
3748-- sliding window implementation. A scan followed by a mapMaybe is also a good
3749-- pattern to express many problems where we want to emit a filtered output and
3750-- not emit an output on every input.
3752-- Passing on of the initial accumulator value to the next fold is equivalent
3753-- to returning the leftover concept.
3756-- | @groupScan splitter fold stream@ folds the input stream using @fold@.
3757-- @splitter@ is applied on the accumulator of the fold every time an item is
3758-- consumed by the fold. The fold continues until @splitter@ returns a 'Just'
3759-- value. A 'Just' result from the @splitter@ specifies a result to be emitted
3760-- in the output stream and the initial value of the accumulator for the next
3761-- group's fold. This allows us to control whether to start fresh for the next
3762-- fold or to continue from the previous fold's output.
3764{-# INLINE groupScan #-}
3766 :: (IsStream t, Monad m)
3767 => (x -> m (Maybe (b, x))) -> Fold m a x -> t m a -> t m b
3768groupScan split fold m = undefined
3771-- | Group the input stream into groups of @n@ elements each and then fold each
3772-- group using the provided fold function.
3774-- >> S.toList $ S.chunksOf 2 FL.sum (S.enumerateFromTo 1 10)
3777-- This can be considered as an n-fold version of 'ltake' where we apply
3778-- 'ltake' repeatedly on the leftover stream until the stream exhausts.
3781{-# INLINE chunksOf #-}
3783 :: (IsStream t, Monad m)
3784 => Int -> Fold m a b -> t m a -> t m b
3785chunksOf n f m = D.fromStreamD $ D.groupsOf n f (D.toStreamD m)
3790{-# INLINE chunksOf2 #-}
3792 :: (IsStream t, Monad m)
3793 => Int -> m c -> Fold2 m c a b -> t m a -> t m b
3794chunksOf2 n action f m = D.fromStreamD $ D.groupsOf2 n action f (D.toStreamD m)
3796-- | @arraysOf n stream@ groups the elements in the input stream into arrays of
3797-- @n@ elements each.
3799-- Same as the following but may be more efficient:
3801-- > arraysOf n = S.chunksOf n (A.writeN n)
3804{-# INLINE arraysOf #-}
3805arraysOf :: (IsStream t, MonadIO m, Storable a)
3806 => Int -> t m a -> t m (Array a)
3807arraysOf n = chunksOf n (writeNUnsafe n)
3809-- XXX we can implement this by repeatedly applying the 'lrunFor' fold.
3810-- XXX add this example after fixing the serial stream rate control
3811-- >>> S.toList $ S.take 5 $ intervalsOf 1 FL.sum $ constRate 2 $ S.enumerateFrom 1
3814-- | Group the input stream into windows of @n@ second each and then fold each
3815-- group using the provided fold function.
3818{-# INLINE intervalsOf #-}
3820 :: (IsStream t, MonadAsync m)
3821 => Double -> Fold m a b -> t m a -> t m b
3823 splitWithSuffix isNothing (FL.lcatMaybes f)
3824 (interjectSuffix n (return Nothing) (Serial.map Just xs))
3826------------------------------------------------------------------------------
3828------------------------------------------------------------------------------
3830-- | @groupsBy cmp f $ S.fromList [a,b,c,...]@ assigns the element @a@ to the
3831-- first group, if @b \`cmp` a@ is 'True' then @b@ is also assigned to the same
3832-- group. If @c \`cmp` a@ is 'True' then @c@ is also assigned to the same
3833-- group and so on. When the comparison fails a new group is started. Each
3834-- group is folded using the fold @f@ and the result of the fold is emitted in
3835-- the output stream.
3837-- >>> S.toList $ S.groupsBy (>) FL.toList $ S.fromList [1,3,7,0,2,5]
3838-- > [[1,3,7],[0,2,5]]
3841{-# INLINE groupsBy #-}
3843 :: (IsStream t, Monad m)
3848groupsBy cmp f m = D.fromStreamD $ D.groupsBy cmp f (D.toStreamD m)
3850-- | Unlike @groupsBy@ this function performs a rolling comparison of two
3851-- successive elements in the input stream. @groupsByRolling cmp f $ S.fromList
3852-- [a,b,c,...]@ assigns the element @a@ to the first group, if @a \`cmp` b@ is
3853-- 'True' then @b@ is also assigned to the same group. If @b \`cmp` c@ is
3854-- 'True' then @c@ is also assigned to the same group and so on. When the
3855-- comparison fails a new group is started. Each group is folded using the fold
3858-- >>> S.toList $ S.groupsByRolling (\a b -> a + 1 == b) FL.toList $ S.fromList [1,2,3,7,8,9]
3859-- > [[1,2,3],[7,8,9]]
3862{-# INLINE groupsByRolling #-}
3864 :: (IsStream t, Monad m)
3869groupsByRolling cmp f m = D.fromStreamD $ D.groupsRollingBy cmp f (D.toStreamD m)
3872-- > groups = groupsBy (==)
3873-- > groups = groupsByRolling (==)
3875-- Groups contiguous spans of equal elements together in individual groups.
3877-- >>> S.toList $ S.groups FL.toList $ S.fromList [1,1,2,2]
3881groups :: (IsStream t, Monad m, Eq a) => Fold m a b -> t m a -> t m b
3882groups = groupsBy (==)
3884------------------------------------------------------------------------------
3885-- N-ary split on a predicate
3886------------------------------------------------------------------------------
3888-- TODO: Use a Splitter configuration similar to the "split" package to make it
3889-- possible to express all splitting combinations. In general, we can have
3890-- infix/suffix/prefix/condensing of separators, dropping both leading/trailing
3891-- separators. We can have a single split operation taking the splitter config
3894-- | Split on an infixed separator element, dropping the separator. Splits the
3895-- stream on separator elements determined by the supplied predicate, separator
3896-- is considered as infixed between two segments, if one side of the separator
3897-- is missing then it is parsed as an empty stream. The supplied 'Fold' is
3898-- applied on the split segments. With '-' representing non-separator elements
3899-- and '.' as separator, 'splitOn' splits as follows:
3902-- "--.--" => "--" "--"
3907-- @splitOn (== x)@ is an inverse of @intercalate (S.yield x)@
3909-- Let's use the following definition for illustration:
3911-- > splitOn' p xs = S.toList $ S.splitOn p (FL.toList) (S.fromList xs)
3913-- >>> splitOn' (== '.') ""
3916-- >>> splitOn' (== '.') "."
3919-- >>> splitOn' (== '.') ".a"
3922-- >>> splitOn' (== '.') "a."
3925-- >>> splitOn' (== '.') "a.b"
3928-- >>> splitOn' (== '.') "a..b"
3933-- This can be considered as an n-fold version of 'breakOn' where we apply
3934-- 'breakOn' successively on the input stream, dropping the first element
3935-- of the second segment after each break.
3937{-# INLINE splitOn #-}
3939 :: (IsStream t, Monad m)
3940 => (a -> Bool) -> Fold m a b -> t m a -> t m b
3941splitOn predicate f m =
3942 D.fromStreamD $ D.splitBy predicate f (D.toStreamD m)
3944-- | Like 'splitOn' but the separator is considered as suffixed to the segments
3945-- in the stream. A missing suffix at the end is allowed. A separator at the
3946-- beginning is parsed as empty segment. With '-' representing elements and
3947-- '.' as separator, 'splitOnSuffix' splits as follows:
3950-- "--.--." => "--" "--"
3951-- "--.--" => "--" "--"
3955-- > splitOnSuffix' p xs = S.toList $ S.splitSuffixBy p (FL.toList) (S.fromList xs)
3957-- >>> splitOnSuffix' (== '.') ""
3960-- >>> splitOnSuffix' (== '.') "."
3963-- >>> splitOnSuffix' (== '.') "a"
3966-- >>> splitOnSuffix' (== '.') ".a"
3969-- >>> splitOnSuffix' (== '.') "a."
3972-- >>> splitOnSuffix' (== '.') "a.b"
3975-- >>> splitOnSuffix' (== '.') "a.b."
3978-- >>> splitOnSuffix' (== '.') "a..b.."
3981-- > lines = splitOnSuffix (== '\n')
3985-- This can be considered as an n-fold version of 'breakPost' where we apply
3986-- 'breakPost' successively on the input stream, dropping the first element
3987-- of the second segment after each break.
3989{-# INLINE splitOnSuffix #-}
3991 :: (IsStream t, Monad m)
3992 => (a -> Bool) -> Fold m a b -> t m a -> t m b
3993splitOnSuffix predicate f m =
3994 D.fromStreamD $ D.splitSuffixBy predicate f (D.toStreamD m)
3996-- | Like 'splitOn' after stripping leading, trailing, and repeated separators.
3997-- Therefore, @".a..b."@ with '.' as the separator would be parsed as
3998-- @["a","b"]@. In other words, its like parsing words from whitespace
4001-- > wordsBy' p xs = S.toList $ S.wordsBy p (FL.toList) (S.fromList xs)
4003-- >>> wordsBy' (== ',') ""
4006-- >>> wordsBy' (== ',') ","
4009-- >>> wordsBy' (== ',') ",a,,b,"
4012-- > words = wordsBy isSpace
4016-- It is equivalent to splitting in any of the infix/prefix/suffix styles
4017-- followed by removal of empty segments.
4018{-# INLINE wordsBy #-}
4020 :: (IsStream t, Monad m)
4021 => (a -> Bool) -> Fold m a b -> t m a -> t m b
4022wordsBy predicate f m =
4023 D.fromStreamD $ D.wordsBy predicate f (D.toStreamD m)
4025-- | Like 'splitOnSuffix' but keeps the suffix attached to the resulting
4028-- > splitWithSuffix' p xs = S.toList $ S.splitWithSuffix p (FL.toList) (S.fromList xs)
4030-- >>> splitWithSuffix' (== '.') ""
4033-- >>> splitWithSuffix' (== '.') "."
4036-- >>> splitWithSuffix' (== '.') "a"
4039-- >>> splitWithSuffix' (== '.') ".a"
4042-- >>> splitWithSuffix' (== '.') "a."
4045-- >>> splitWithSuffix' (== '.') "a.b"
4048-- >>> splitWithSuffix' (== '.') "a.b."
4051-- >>> splitWithSuffix' (== '.') "a..b.."
4052-- > ["a.",".","b.","."]
4056-- This can be considered as an n-fold version of 'breakPost' where we apply
4057-- 'breakPost' successively on the input stream.
4059{-# INLINE splitWithSuffix #-}
4061 :: (IsStream t, Monad m)
4062 => (a -> Bool) -> Fold m a b -> t m a -> t m b
4063splitWithSuffix predicate f m =
4064 D.fromStreamD $ D.splitSuffixBy' predicate f (D.toStreamD m)
4066------------------------------------------------------------------------------
4067-- Split on a delimiter sequence
4068------------------------------------------------------------------------------
4070-- Int list examples for splitOn:
4072-- >>> splitList [] [1,2,3,3,4]
4073-- > [[1],[2],[3],[3],[4]]
4075-- >>> splitList [5] [1,2,3,3,4]
4078-- >>> splitList [1] [1,2,3,3,4]
4081-- >>> splitList [4] [1,2,3,3,4]
4084-- >>> splitList [2] [1,2,3,3,4]
4087-- >>> splitList [3] [1,2,3,3,4]
4090-- >>> splitList [3,3] [1,2,3,3,4]
4093-- >>> splitList [1,2,3,3,4] [1,2,3,3,4]
4096-- | Like 'splitOn' but the separator is a sequence of elements instead of a
4099-- For illustration, let's define a function that operates on pure lists:
4102-- splitOnSeq' pat xs = S.toList $ S.splitOnSeq (A.fromList pat) (FL.toList) (S.fromList xs)
4105-- >>> splitOnSeq' "" "hello"
4106-- > ["h","e","l","l","o"]
4108-- >>> splitOnSeq' "hello" ""
4111-- >>> splitOnSeq' "hello" "hello"
4114-- >>> splitOnSeq' "x" "hello"
4117-- >>> splitOnSeq' "h" "hello"
4120-- >>> splitOnSeq' "o" "hello"
4123-- >>> splitOnSeq' "e" "hello"
4126-- >>> splitOnSeq' "l" "hello"
4129-- >>> splitOnSeq' "ll" "hello"
4132-- 'splitOnSeq' is an inverse of 'intercalate'. The following law always holds:
4134-- > intercalate . splitOn == id
4136-- The following law holds when the separator is non-empty and contains none of
4137-- the elements present in the input lists:
4139-- > splitOn . intercalate == id
4143-- XXX We can use a polymorphic vector implemented by Array# to represent the
4144-- sequence, that way we can avoid the Storable constraint. If we still need
4145-- Storable Array for performance, we can use a separate splitOnArray API for
4146-- that. We can also have an API where the sequence itself is a lazy stream, so
4147-- that we can search files in files for example.
4148{-# INLINE splitOnSeq #-}
4150 :: (IsStream t, MonadIO m, Storable a, Enum a, Eq a)
4151 => Array a -> Fold m a b -> t m a -> t m b
4152splitOnSeq patt f m = D.fromStreamD $ D.splitOn patt f (D.toStreamD m)
4155-- This can be implemented easily using Rabin Karp
4156-- | Split on any one of the given patterns.
4157{-# INLINE splitOnAny #-}
4159 :: (IsStream t, Monad m, Storable a, Integral a)
4160 => [Array a] -> Fold m a b -> t m a -> t m b
4161splitOnAny subseq f m = undefined -- D.fromStreamD $ D.splitOnAny f subseq (D.toStreamD m)
4164-- | Like 'splitSuffixBy' but the separator is a sequence of elements, instead
4165-- of a predicate for a single element.
4167-- > splitSuffixOn_ pat xs = S.toList $ S.splitSuffixOn (A.fromList pat) (FL.toList) (S.fromList xs)
4169-- >>> splitSuffixOn_ "." ""
4172-- >>> splitSuffixOn_ "." "."
4175-- >>> splitSuffixOn_ "." "a"
4178-- >>> splitSuffixOn_ "." ".a"
4181-- >>> splitSuffixOn_ "." "a."
4184-- >>> splitSuffixOn_ "." "a.b"
4187-- >>> splitSuffixOn_ "." "a.b."
4190-- >>> splitSuffixOn_ "." "a..b.."
4193-- > lines = splitSuffixOn "\n"
4196{-# INLINE splitOnSuffixSeq #-}
4198 :: (IsStream t, MonadIO m, Storable a, Enum a, Eq a)
4199 => Array a -> Fold m a b -> t m a -> t m b
4200splitOnSuffixSeq patt f m =
4201 D.fromStreamD $ D.splitSuffixOn False patt f (D.toStreamD m)
4204-- | Like 'splitOn' but drops any empty splits.
4206{-# INLINE wordsOn #-}
4208 :: (IsStream t, Monad m, Storable a, Eq a)
4209 => Array a -> Fold m a b -> t m a -> t m b
4210wordsOn subseq f m = undefined -- D.fromStreamD $ D.wordsOn f subseq (D.toStreamD m)
4213-- XXX use a non-monadic intersperse to remove the MonadAsync constraint.
4215-- | Like 'splitOnSeq' but splits the separator as well, as an infix token.
4217-- > splitOn'_ pat xs = S.toList $ S.splitOn' (A.fromList pat) (FL.toList) (S.fromList xs)
4219-- >>> splitOn'_ "" "hello"
4220-- > ["h","","e","","l","","l","","o"]
4222-- >>> splitOn'_ "hello" ""
4225-- >>> splitOn'_ "hello" "hello"
4228-- >>> splitOn'_ "x" "hello"
4231-- >>> splitOn'_ "h" "hello"
4234-- >>> splitOn'_ "o" "hello"
4237-- >>> splitOn'_ "e" "hello"
4240-- >>> splitOn'_ "l" "hello"
4241-- > ["he","l","","l","o"]
4243-- >>> splitOn'_ "ll" "hello"
4247{-# INLINE splitBySeq #-}
4249 :: (IsStream t, MonadAsync m, Storable a, Enum a, Eq a)
4250 => Array a -> Fold m a b -> t m a -> t m b
4251splitBySeq patt f m =
4252 intersperseM (fold f (A.toStream patt)) $ splitOnSeq patt f m
4254-- | Like 'splitSuffixOn' but keeps the suffix intact in the splits.
4256-- > splitSuffixOn'_ pat xs = S.toList $ FL.splitSuffixOn' (A.fromList pat) (FL.toList) (S.fromList xs)
4258-- >>> splitSuffixOn'_ "." ""
4261-- >>> splitSuffixOn'_ "." "."
4264-- >>> splitSuffixOn'_ "." "a"
4267-- >>> splitSuffixOn'_ "." ".a"
4270-- >>> splitSuffixOn'_ "." "a."
4273-- >>> splitSuffixOn'_ "." "a.b"
4276-- >>> splitSuffixOn'_ "." "a.b."
4279-- >>> splitSuffixOn'_ "." "a..b.."
4280-- > ["a.",".","b.","."]
4283{-# INLINE splitWithSuffixSeq #-}
4285 :: (IsStream t, MonadIO m, Storable a, Enum a, Eq a)
4286 => Array a -> Fold m a b -> t m a -> t m b
4287splitWithSuffixSeq patt f m =
4288 D.fromStreamD $ D.splitSuffixOn True patt f (D.toStreamD m)
4291-- This can be implemented easily using Rabin Karp
4292-- | Split post any one of the given patterns.
4293{-# INLINE splitSuffixOnAny #-}
4295 :: (IsStream t, Monad m, Storable a, Integral a)
4296 => [Array a] -> Fold m a b -> t m a -> t m b
4297splitSuffixOnAny subseq f m = undefined
4298 -- D.fromStreamD $ D.splitPostAny f subseq (D.toStreamD m)
4301------------------------------------------------------------------------------
4303------------------------------------------------------------------------------
4305-- | @splitInnerBy splitter joiner stream@ splits the inner containers @f a@ of
4306-- an input stream @t m (f a)@ using the @splitter@ function. Container
4307-- elements @f a@ are collected until a split occurs, then all the elements
4308-- before the split are joined using the @joiner@ function.
4310-- For example, if we have a stream of @Array Word8@, we may want to split the
4311-- stream into arrays representing lines separated by '\n' byte such that the
4312-- resulting stream after a split would be one array for each line.
4314-- CAUTION! This is not a true streaming function as the container size after
4315-- the split and merge may not be bounded.
4318{-# INLINE splitInnerBy #-}
4320 :: (IsStream t, Monad m)
4321 => (f a -> m (f a, Maybe (f a))) -- splitter
4322 -> (f a -> f a -> m (f a)) -- joiner
4325splitInnerBy splitter joiner xs =
4326 D.fromStreamD $ D.splitInnerBy splitter joiner $ D.toStreamD xs
4328-- | Like 'splitInnerBy' but splits assuming the separator joins the segment in
4332{-# INLINE splitInnerBySuffix #-}
4334 :: (IsStream t, Monad m, Eq (f a), Monoid (f a))
4335 => (f a -> m (f a, Maybe (f a))) -- splitter
4336 -> (f a -> f a -> m (f a)) -- joiner
4339splitInnerBySuffix splitter joiner xs =
4340 D.fromStreamD $ D.splitInnerBySuffix splitter joiner $ D.toStreamD xs
4342------------------------------------------------------------------------------
4343-- Reorder in sequence
4344------------------------------------------------------------------------------
4347-- Buffer until the next element in sequence arrives. The function argument
4348-- determines the difference in sequence numbers. This could be useful in
4349-- implementing sequenced streams, for example, TCP reassembly.
4350{-# INLINE reassembleBy #-}
4352 :: (IsStream t, Monad m)
4357reassembleBy = undefined
4360------------------------------------------------------------------------------
4362------------------------------------------------------------------------------
4364-- | Tap the data flowing through a stream into a 'Fold'. For example, you may
4365-- add a tap to log the contents flowing through the stream. The fold is used
4366-- only for effects, its result is discarded.
4371-- -----stream m a ---------------stream m a-----
4376-- > S.drain $ S.tap (FL.drainBy print) (S.enumerateFromTo 1 2)
4381-- Compare with 'trace'.
4385tap :: (IsStream t, Monad m) => FL.Fold m a b -> t m a -> t m a
4386tap f xs = D.fromStreamD $ D.tap f (D.toStreamD xs)
4388-- | @tapOffsetEvery offset n@ taps every @n@th element in the stream
4389-- starting at @offset@. @offset@ can be between @0@ and @n - 1@. Offset 0
4390-- means start at the first element in the stream. If the offset is outside
4391-- this range then @offset `mod` n@ is used as offset.
4394-- >>> S.drain $ S.tapOffsetEvery 0 2 (FL.mapM print FL.toList) $ S.enumerateFromTo 0 10
4400{-# INLINE tapOffsetEvery #-}
4401tapOffsetEvery :: (IsStream t, Monad m)
4402 => Int -> Int -> FL.Fold m a b -> t m a -> t m a
4403tapOffsetEvery offset n f xs =
4404 D.fromStreamD $ D.tapOffsetEvery offset n f (D.toStreamD xs)
4406-- | Redirect a copy of the stream to a supplied fold and run it concurrently
4407-- in an independent thread. The fold may buffer some elements. The buffer size
4408-- is determined by the prevailing 'maxBuffer' setting.
4413-- -----stream m a ---------------stream m a-----
4418-- > S.drain $ S.tapAsync (S.mapM_ print) (S.enumerateFromTo 1 2)
4423-- Exceptions from the concurrently running fold are propagated to the current
4424-- computation. Note that, because of buffering in the fold, exceptions may be
4425-- delayed and may not correspond to the current element being processed in the
4426-- parent stream, but we guarantee that before the parent stream stops the tap
4427-- finishes and all exceptions from it are drained.
4430-- Compare with 'tap'.
4433{-# INLINE tapAsync #-}
4434tapAsync :: (IsStream t, MonadAsync m) => FL.Fold m a b -> t m a -> t m a
4435tapAsync f xs = D.fromStreamD $ D.tapAsync f (D.toStreamD xs)
4437-- | @pollCounts predicate transform fold stream@ counts those elements in the
4438-- stream that pass the @predicate@. The resulting count stream is sent to
4439-- another thread which transforms it using @transform@ and then folds it using
4440-- @fold@. The thread is automatically cleaned up if the stream stops or
4441-- aborts due to exception.
4443-- For example, to print the count of elements processed every second:
4446-- > S.drain $ S.pollCounts (const True) (S.rollingMap (-) . S.delayPost 1) (FL.drainBy print)
4447-- $ S.enumerateFrom 0
4450-- Note: This may not work correctly on 32-bit machines.
4454{-# INLINE pollCounts #-}
4456 (IsStream t, MonadAsync m)
4458 -> (t m Int -> t m Int)
4462pollCounts predicate transf f xs =
4464 $ D.pollCounts predicate (D.toStreamD . transf . D.fromStreamD) f
4467-- | Calls the supplied function with the number of elements consumed
4468-- every @n@ seconds. The given function is run in a separate thread
4469-- until the end of the stream. In case there is an exception in the
4470-- stream the thread is killed during the next major GC.
4472-- Note: The action is not guaranteed to run if the main thread exits.
4475-- > delay n = threadDelay (round $ n * 1000000) >> return n
4476-- > S.drain $ S.tapRate 2 (\\n -> print $ show n ++ " elements processed") (delay 1 S.|: delay 0.5 S.|: delay 0.5 S.|: S.nil)
4477-- 2 elements processed
4478-- 1 elements processed
4481-- Note: This may not work correctly on 32-bit machines.
4484{-# INLINE tapRate #-}
4486 (IsStream t, MonadAsync m, MonadCatch m)
4491tapRate n f xs = D.fromStreamD $ D.tapRate n f $ D.toStreamD xs
4493-- | Apply a monadic function to each element flowing through the stream and
4494-- discard the results.
4497-- > S.drain $ S.trace print (S.enumerateFromTo 1 2)
4502-- Compare with 'tap'.
4506trace :: (IsStream t, MonadAsync m) => (a -> m b) -> t m a -> t m a
4507trace f = mapM (\x -> void (f x) >> return x)
4509-- | Perform a side effect before yielding each element of the stream and
4510-- discard the results.
4513-- > S.drain $ S.trace_ (print "got here") (S.enumerateFromTo 1 2)
4518-- See also: 'trace', 'interspersePrefix_'
4521{-# INLINE trace_ #-}
4522trace_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
4523trace_ eff = Serial.mapM (\x -> eff >> return x)
4525------------------------------------------------------------------------------
4526-- Windowed classification
4527------------------------------------------------------------------------------
4529-- We divide the stream into windows or chunks in space or time and each window
4530-- can be associated with a key, all events associated with a particular key in
4531-- the window can be folded to a single result. The stream can be split into
4532-- windows by size or by using a split predicate on the elements in the stream.
4533-- For example, when we receive a closing flag, we can close the window.
4535-- A "chunk" is a space window and a "session" is a time window. Are there any
4536-- other better short words to describe them. An alternative is to use
4537-- "swindow" and "twindow". Another word for "session" could be "spell".
4539-- TODO: To mark the position in space or time we can have Indexed or
4540-- TimeStamped types. That can make it easy to deal with the position indices
4543------------------------------------------------------------------------------
4544-- Keyed Sliding Windows
4545------------------------------------------------------------------------------
4548{-# INLINABLE classifySlidingChunks #-}
4549classifySlidingChunks
4550 :: (IsStream t, MonadAsync m, Ord k)
4551 => Int -- ^ window size
4552 -> Int -- ^ window slide
4553 -> Fold m a b -- ^ Fold to be applied to window events
4554 -> t m (k, a, Bool) -- ^ window key, data, close event
4556classifySlidingChunks wsize wslide (Fold step initial extract) str
4559-- XXX Another variant could be to slide the window on an event, e.g. in TCP we
4560-- slide the send window when an ack is received and we slide the receive
4561-- window when a sequence is complete. Sliding is stateful in case of TCP,
4562-- sliding releases the send buffer or makes data available to the user from
4563-- the receive buffer.
4564{-# INLINABLE classifySlidingSessions #-}
4565classifySlidingSessions
4566 :: (IsStream t, MonadAsync m, Ord k)
4567 => Double -- ^ timer tick in seconds
4568 -> Double -- ^ time window size
4569 -> Double -- ^ window slide
4570 -> Fold m a b -- ^ Fold to be applied to window events
4571 -> t m (k, a, Bool, AbsTime) -- ^ window key, data, close flag, timestamp
4573classifySlidingSessions tick interval slide (Fold step initial extract) str
4577------------------------------------------------------------------------------
4578-- Sliding Window Buffers
4579------------------------------------------------------------------------------
4581-- These buffered versions could be faster than concurrent incremental folds of
4582-- all overlapping windows as in many cases we may not need all the values to
4583-- compute the fold, we can just compute the result using the old value and new
4584-- value. However, we may need the buffer once in a while, for example for
4585-- string search we usually compute the hash incrementally but when the hash
4586-- matches the hash of the pattern we need to compare the whole string.
4588-- XXX we should be able to implement sequence based splitting combinators
4589-- using this combinator.
4592-- | Buffer n elements of the input in a ring buffer. When t new elements are
4593-- collected, slide the window to remove the same number of oldest elements,
4594-- insert the new elements, and apply an incremental fold on the sliding
4595-- window, supplying the outgoing elements, the new ring buffer as arguments.
4597 :: (IsStream t, Monad m, Ord a, Storable a)
4598 => Int -- window size
4599 -> Int -- window slide
4600 -> Fold m (Ring a, Array a) b
4603slidingChunkBuffer = undefined
4605-- Buffer n seconds worth of stream elements of the input in a radix tree.
4606-- Every t seconds, remove the items that are older than n seconds, and apply
4607-- an incremental fold on the sliding window, supplying the outgoing elements,
4608-- and the new radix tree buffer as arguments.
4610 :: (IsStream t, Monad m, Ord a, Storable a)
4611 => Int -- window size
4613 -> Fold m (RTree a, Array a) b
4616slidingSessionBuffer = undefined
4619------------------------------------------------------------------------------
4620-- Keyed Session Windows
4621------------------------------------------------------------------------------
4624-- | Keyed variable size space windows. Close the window if we do not receive a
4625-- window event in the next "spaceout" elements.
4626{-# INLINABLE classifyChunksBy #-}
4628 :: (IsStream t, MonadAsync m, Ord k)
4629 => Int -- ^ window spaceout (spread)
4630 -> Bool -- ^ reset the spaceout when a chunk window element is received
4631 -> Fold m a b -- ^ Fold to be applied to chunk window elements
4632 -> t m (k, a, Bool) -- ^ chunk key, data, last element
4634classifyChunksBy spanout reset (Fold step initial extract) str = undefined
4636-- | Like 'classifyChunksOf' but the chunk size is reset if an element is
4637-- received within the chunk size window. The chunk gets closed only if no
4638-- element is received within the chunk window.
4640{-# INLINABLE classifyKeepAliveChunks #-}
4641classifyKeepAliveChunks
4642 :: (IsStream t, MonadAsync m, Ord k)
4643 => Int -- ^ window spaceout (spread)
4644 -> Fold m a b -- ^ Fold to be applied to chunk window elements
4645 -> t m (k, a, Bool) -- ^ chunk key, data, last element
4647classifyKeepAliveChunks spanout = classifyChunksBy spanout True
4650data SessionState t m k a b = SessionState
4651 { sessionCurTime :: !AbsTime -- ^ time since last event
4652 , sessionEventTime :: !AbsTime -- ^ time as per last event
4653 , sessionCount :: !Int -- ^ total number sessions in progress
4654 , sessionTimerHeap :: H.Heap (H.Entry AbsTime k) -- ^ heap for timeouts
4655 , sessionKeyValueMap :: Map.Map k a -- ^ Stored sessions for keys
4656 , sessionOutputStream :: t (m :: Type -> Type) (k, b) -- ^ Completed sessions
4661-- | @classifySessionsBy tick timeout idle pred f stream@ groups timestamped
4662-- events in an input event stream into sessions based on a session key. Each
4663-- element in the stream is an event consisting of a triple @(session key,
4664-- sesssion data, timestamp)@. @session key@ is a key that uniquely identifies
4665-- the session. All the events belonging to a session are folded using the
4666-- fold @f@ until the fold returns a 'Left' result or a timeout has occurred.
4667-- The session key and the result of the fold are emitted in the output stream
4668-- when the session is purged.
4670-- When @idle@ is 'False', @timeout@ is the maximum lifetime of a session in
4671-- seconds, measured from the @timestamp@ of the first event in that session.
4672-- When @idle@ is 'True' then the timeout is an idle timeout, it is reset after
4673-- every event received in the session.
4675-- @timestamp@ in an event characterizes the time when the input event was
4676-- generated, this is an absolute time measured from some @Epoch@. The notion
4677-- of current time is maintained by a monotonic event time clock using the
4678-- timestamps seen in the input stream. The latest timestamp seen till now is
4679-- used as the base for the current time. When no new events are seen, a timer
4680-- is started with a tick duration specified by @tick@. This timer is used to
4681-- detect session timeouts in the absence of new events.
4683-- The predicate @pred@ is invoked with the current session count, if it
4684-- returns 'True' a session is ejected from the session cache before inserting
4685-- a new session. This could be useful to alert or eject sessions when the
4686-- number of sessions becomes too high.
4691-- XXX Perhaps we should use an "Event a" type to represent timestamped data.
4692{-# INLINABLE classifySessionsBy #-}
4694 :: (IsStream t, MonadAsync m, Ord k)
4695 => Double -- ^ timer tick in seconds
4696 -> Double -- ^ session timeout in seconds
4697 -> Bool -- ^ reset the timeout when an event is received
4698 -> (Int -> m Bool) -- ^ predicate to eject sessions based on session count
4699 -> Fold m a (Either b b) -- ^ Fold to be applied to session events
4700 -> t m (k, a, AbsTime) -- ^ session key, data, timestamp
4701 -> t m (k, b) -- ^ session key, fold result
4702classifySessionsBy tick tmout reset ejectPred
4703 (Fold step initial extract) str =
4704 concatMap sessionOutputStream $
4705 scanlMAfter' sstep (return szero) flush stream
4709 timeoutMs = toRelTime (round (tmout * 1000) :: MilliSecond64)
4710 tickMs = toRelTime (round (tick * 1000) :: MilliSecond64)
4711 szero = SessionState
4712 { sessionCurTime = toAbsTime (0 :: MilliSecond64)
4713 , sessionEventTime = toAbsTime (0 :: MilliSecond64)
4715 , sessionTimerHeap = H.empty
4716 , sessionKeyValueMap = Map.empty
4717 , sessionOutputStream = K.nil
4720 -- We can eject sessions based on the current session count to limit
4721 -- memory consumption. There are two possible strategies:
4723 -- 1) Eject old sessions or sessions beyond a certain/lower timeout
4724 -- threshold even before timeout, effectively reduce the timeout.
4725 -- 2) Drop creation of new sessions but keep accepting new events for the
4728 -- We use the first strategy as of now.
4730 -- Got a new stream input element
4731 sstep session@SessionState{..} (Just (key, value, timestamp)) = do
4732 -- XXX we should use a heap in pinned memory to scale it to a large
4735 -- To detect session inactivity we keep a timestamp of the latest event
4736 -- in the Map along with the fold result. When we purge the session
4737 -- from the heap we match the timestamp in the heap with the timestamp
4738 -- in the Map, if the latest timestamp is newer and has not expired we
4739 -- reinsert the key in the heap.
4741 -- XXX if the key is an Int, we can also use an IntMap for slightly
4742 -- better performance.
4744 let curTime = max sessionEventTime timestamp
4748 Just (Tuple' _ acc) -> return acc
4749 new <- step old value
4750 return $ Tuple' timestamp new
4751 mOld = Map.lookup key sessionKeyValueMap
4753 acc@(Tuple' _ fres) <- accumulate mOld
4757 -- deleting a key from the heap is expensive, so we never
4758 -- delete a key from heap, we just purge it from the Map and it
4759 -- gets purged from the heap on timeout. We just need an extra
4760 -- lookup in the Map when the key is purged from the heap, that
4761 -- should not be expensive.
4763 let (mp, cnt) = case mOld of
4764 Nothing -> (sessionKeyValueMap, sessionCount)
4765 Just _ -> (Map.delete key sessionKeyValueMap
4768 { sessionCurTime = curTime
4769 , sessionEventTime = curTime
4770 , sessionCount = cnt
4771 , sessionKeyValueMap = mp
4772 , sessionOutputStream = yield (key, x)
4775 (hp1, mp1, out1, cnt1) <- do
4776 let vars = (sessionTimerHeap, sessionKeyValueMap,
4777 K.nil, sessionCount)
4779 -- inserting new entry
4781 -- Eject a session from heap and map is needed
4782 eject <- ejectPred sessionCount
4783 (hp, mp, out, cnt) <-
4788 -- Insert the new session in heap
4789 let expiry = addToAbsTime timestamp timeoutMs
4790 hp' = H.insert (Entry expiry key) hp
4791 in return (hp', mp, out, cnt + 1)
4792 -- updating old entry
4793 Just _ -> return vars
4795 let mp2 = Map.insert key acc mp1
4796 return $ SessionState
4797 { sessionCurTime = curTime
4798 , sessionEventTime = curTime
4799 , sessionCount = cnt1
4800 , sessionTimerHeap = hp1
4801 , sessionKeyValueMap = mp2
4802 , sessionOutputStream = out1
4805 -- Got a timer tick event
4806 sstep sessionState@SessionState{..} Nothing =
4807 let curTime = addToAbsTime sessionCurTime tickMs
4808 in ejectExpired sessionState curTime
4810 flush session@SessionState{..} = do
4811 (hp', mp', out, count) <-
4814 , sessionKeyValueMap
4819 { sessionCount = count
4820 , sessionTimerHeap = hp'
4821 , sessionKeyValueMap = mp'
4822 , sessionOutputStream = out
4830 -- delete from map and output the fold accumulator
4831 ejectEntry hp mp out cnt acc key = do
4833 let out1 = (key, fromEither sess) `K.cons` out
4834 let mp1 = Map.delete key mp
4835 return (hp, mp1, out1, cnt - 1)
4837 ejectAll (hp, mp, out, !cnt) = do
4838 let hres = H.uncons hp
4840 Just (Entry _ key, hp1) -> do
4841 r <- case Map.lookup key mp of
4842 Nothing -> return (hp1, mp, out, cnt)
4843 Just (Tuple' _ acc) -> ejectEntry hp1 mp out cnt acc key
4846 assert (Map.null mp) (return ())
4847 return (hp, mp, out, cnt)
4849 ejectOne (hp, mp, out, !cnt) = do
4850 let hres = H.uncons hp
4852 Just (Entry expiry key, hp1) ->
4853 case Map.lookup key mp of
4854 Nothing -> ejectOne (hp1, mp, out, cnt)
4855 Just (Tuple' latestTS acc) -> do
4856 let expiry1 = addToAbsTime latestTS timeoutMs
4857 if not reset || expiry1 <= expiry
4858 then ejectEntry hp1 mp out cnt acc key
4860 -- reset the session timeout and continue
4861 let hp2 = H.insert (Entry expiry1 key) hp1
4862 in ejectOne (hp2, mp, out, cnt)
4864 assert (Map.null mp) (return ())
4865 return (hp, mp, out, cnt)
4867 ejectExpired session@SessionState{..} curTime = do
4868 (hp', mp', out, count) <-
4869 ejectLoop sessionTimerHeap sessionKeyValueMap K.nil sessionCount
4871 { sessionCurTime = curTime
4872 , sessionCount = count
4873 , sessionTimerHeap = hp'
4874 , sessionKeyValueMap = mp'
4875 , sessionOutputStream = out
4880 ejectLoop hp mp out !cnt = do
4881 let hres = H.uncons hp
4883 Just (Entry expiry key, hp1) -> do
4885 if curTime >= expiry
4886 then return (True, False)
4892 case Map.lookup key mp of
4893 Nothing -> ejectLoop hp1 mp out cnt
4894 Just (Tuple' latestTS acc) -> do
4895 let expiry1 = addToAbsTime latestTS timeoutMs
4896 if expiry1 <= curTime || not reset || force
4898 (hp2,mp1,out1,cnt1) <-
4899 ejectEntry hp1 mp out cnt acc key
4900 ejectLoop hp2 mp1 out1 cnt1
4902 -- reset the session timeout and continue
4903 let hp2 = H.insert (Entry expiry1 key) hp1
4904 in ejectLoop hp2 mp out cnt
4905 else return (hp, mp, out, cnt)
4907 assert (Map.null mp) (return ())
4908 return (hp, mp, out, cnt)
4910 -- merge timer events in the stream
4911 stream = Serial.map Just str `Par.parallelFst` repeatM timer
4913 liftIO $ threadDelay (round $ tick * 1000000)
4916-- | Like 'classifySessionsOf' but the session is kept alive if an event is
4917-- received within the session window. The session times out and gets closed
4918-- only if no event is received within the specified session window size.
4920-- If the ejection predicate returns 'True', the session that was idle for
4921-- the longest time is ejected before inserting a new session.
4924-- classifyKeepAliveSessions timeout pred = classifySessionsBy 1 timeout True pred
4929{-# INLINABLE classifyKeepAliveSessions #-}
4930classifyKeepAliveSessions
4931 :: (IsStream t, MonadAsync m, Ord k)
4932 => Double -- ^ session inactive timeout
4933 -> (Int -> m Bool) -- ^ predicate to eject sessions on session count
4934 -> Fold m a (Either b b) -- ^ Fold to be applied to session payload data
4935 -> t m (k, a, AbsTime) -- ^ session key, data, timestamp
4937classifyKeepAliveSessions tmout =
4938 classifySessionsBy 1 tmout True
4940------------------------------------------------------------------------------
4941-- Keyed tumbling windows
4942------------------------------------------------------------------------------
4944-- Tumbling windows is a special case of sliding windows where the window slide
4945-- is the same as the window size. Or it can be a special case of session
4946-- windows where the reset flag is set to False.
4948-- XXX instead of using the early termination flag in the stream, we can use an
4949-- early terminating fold instead.
4952-- | Split the stream into fixed size chunks of specified size. Within each
4953-- such chunk fold the elements in buckets identified by the keys. A particular
4954-- bucket fold can be terminated early if a closing flag is encountered in an
4955-- element for that key.
4958{-# INLINABLE classifyChunksOf #-}
4960 :: (IsStream t, MonadAsync m, Ord k)
4961 => Int -- ^ window size
4962 -> Fold m a b -- ^ Fold to be applied to window events
4963 -> t m (k, a, Bool) -- ^ window key, data, close event
4965classifyChunksOf wsize = classifyChunksBy wsize False
4968-- | Split the stream into fixed size time windows of specified interval in
4969-- seconds. Within each such window, fold the elements in sessions identified
4970-- by the session keys. The fold result is emitted in the output stream if the
4971-- fold returns a 'Left' result or if the time window ends.
4973-- Session @timestamp@ in the input stream is an absolute time from some epoch,
4974-- characterizing the time when the input element was generated. To detect
4975-- session window end, a monotonic event time clock is maintained synced with
4976-- the timestamps with a clock resolution of 1 second.
4978-- If the ejection predicate returns 'True', the session with the longest
4979-- lifetime is ejected before inserting a new session.
4982-- classifySessionsOf interval pred = classifySessionsBy 1 interval False pred
4987-- $ S.classifySessionsOf 3 (const (return False)) (fmap Right FL.toList)
4988-- $ S.map (\(ts,(k,a)) -> (k, a, ts))
4991-- $ (,) <$> S.fromList [1,2,3] <*> S.fromList [1,2,3]
4996{-# INLINABLE classifySessionsOf #-}
4998 :: (IsStream t, MonadAsync m, Ord k)
4999 => Double -- ^ time window size
5000 -> (Int -> m Bool) -- ^ predicate to eject sessions on session count
5001 -> Fold m a (Either b b) -- ^ Fold to be applied to session events
5002 -> t m (k, a, AbsTime) -- ^ session key, data, timestamp
5004classifySessionsOf interval =
5005 classifySessionsBy 1 interval False
5007------------------------------------------------------------------------------
5009------------------------------------------------------------------------------
5011-- | Run a side effect before the stream yields its first element.
5013-- > before action xs = 'nilM' action <> xs
5016{-# INLINE before #-}
5017before :: (IsStream t, Monad m) => m b -> t m a -> t m a
5018before action xs = D.fromStreamD $ D.before action $ D.toStreamD xs
5020-- | Run a side effect at the end of the stream. The side effect won't run if
5021-- the stream is garbage collected before it reached the end.
5023-- > after_ action xs = xs <> 'nilM' action
5025-- This has slightly better performance than 'after'.
5029{-# INLINE after_ #-}
5030after_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
5031after_ action xs = D.fromStreamD $ D.after_ action $ D.toStreamD xs
5033-- | Run a side effect at the end of the stream or if it is garbage collected
5034-- even before reaching the end.
5039after :: (IsStream t, MonadIO m, MonadBaseControl IO m)
5040 => m b -> t m a -> t m a
5041after action xs = D.fromStreamD $ D.after action $ D.toStreamD xs
5043-- | Run a side effect whenever the stream aborts due to an exception.
5046{-# INLINE onException #-}
5047onException :: (IsStream t, MonadCatch m) => m b -> t m a -> t m a
5048onException action xs = D.fromStreamD $ D.onException action $ D.toStreamD xs
5050-- | Run a side effect at the end of the stream or if it aborts due to an
5051-- exception before it could reach the end. The side effect is not run if the
5052-- stream is garbage collected before reaching the end.
5054-- This has slightly better performance than 'finally'.
5058{-# INLINE finally_ #-}
5059finally_ :: (IsStream t, MonadCatch m) => m b -> t m a -> t m a
5060finally_ action xs = D.fromStreamD $ D.finally_ action $ D.toStreamD xs
5062-- | Run a side effect at the end of the stream, or if it aborts due to an
5063-- exception or if it is garbage collected before it could reach the end.
5067{-# INLINE finally #-}
5068finally :: (IsStream t, MonadAsync m, MonadCatch m) => m b -> t m a -> t m a
5069finally action xs = D.fromStreamD $ D.finally action $ D.toStreamD xs
5071-- | Run the first action before the stream starts and remember its output,
5072-- generate a stream using the output, run the second action using the
5073-- remembered value as an argument whenever the stream ends normally or due to
5074-- an exception. The second action won't run if the stream is garbage collected
5075-- before it could reach the end.
5077-- This has slightly better performance than 'bracket'.
5081{-# INLINE bracket_ #-}
5082bracket_ :: (IsStream t, MonadCatch m)
5083 => m b -> (b -> m c) -> (b -> t m a) -> t m a
5084bracket_ bef aft bet = D.fromStreamD $
5085 D.bracket_ bef aft (toStreamD . bet)
5087-- | Run the first action before the stream starts and remember its output,
5088-- generate a stream using the output, run the second action using the
5089-- remembered value as an argument whenever the stream ends normally, due to
5090-- an exception or if it is garbage collected after a partial lazy evaluation.
5094{-# INLINE bracket #-}
5095bracket :: (IsStream t, MonadAsync m, MonadCatch m)
5096 => m b -> (b -> m c) -> (b -> t m a) -> t m a
5097bracket bef aft bet = D.fromStreamD $
5098 D.bracket bef aft (toStreamD . bet)
5100-- | When evaluating a stream if an exception occurs, stream evaluation aborts
5101-- and the specified exception handler is run with the exception as argument.
5104{-# INLINE handle #-}
5105handle :: (IsStream t, MonadCatch m, Exception e)
5106 => (e -> t m a) -> t m a -> t m a
5108 D.fromStreamD $ D.handle (D.toStreamD . handler) $ D.toStreamD xs
5110-- Keep concating either streams as long as rights are generated, stop as soon
5111-- as a left is generated and concat the left stream.
5113-- See also: 'handle'
5119 :: -- (IsStream t, MonadAsync m) =>
5120 (forall x. t m x -> t m x -> t m x)
5121 -> (a -> t m (Either (t m b) b))
5124concatMapEitherWith = undefined
5127------------------------------------------------------------------------------
5128-- Generalize the underlying monad
5129------------------------------------------------------------------------------
5131-- | Transform the inner monad of a stream using a natural transformation.
5136hoist :: (Monad m, Monad n)
5137 => (forall x. m x -> n x) -> SerialT m a -> SerialT n a
5138hoist f xs = fromStreamS $ S.hoist f (toStreamS xs)
5140-- | Generalize the inner monad of the stream from 'Identity' to any monad.
5144{-# INLINE generally #-}
5145generally :: (IsStream t, Monad m) => t Identity a -> t m a
5146generally xs = fromStreamS $ S.hoist (return . runIdentity) (toStreamS xs)
5148------------------------------------------------------------------------------
5149-- Add and remove a monad transformer
5150------------------------------------------------------------------------------
5152-- | Lift the inner monad @m@ of a stream @t m a@ to @tr m@ using the monad
5157{-# INLINE liftInner #-}
5158liftInner :: (Monad m, IsStream t, MonadTrans tr, Monad (tr m))
5159 => t m a -> t (tr m) a
5160liftInner xs = fromStreamD $ D.liftInner (toStreamD xs)
5162------------------------------------------------------------------------------
5163-- Sharing read only state in a stream
5164------------------------------------------------------------------------------
5166-- | Evaluate the inner monad of a stream as 'ReaderT'.
5170{-# INLINE runReaderT #-}
5171runReaderT :: (IsStream t, Monad m) => m s -> t (ReaderT s m) a -> t m a
5172runReaderT s xs = fromStreamD $ D.runReaderT s (toStreamD xs)
5174-- | Run a stream transformation using a given environment.
5176-- See also: 'Serial.map'
5180{-# INLINE usingReaderT #-}
5182 :: (Monad m, IsStream t)
5184 -> (t (ReaderT r m) a -> t (ReaderT r m) a)
5187usingReaderT r f xs = runReaderT r $ f $ liftInner xs
5189------------------------------------------------------------------------------
5190-- Sharing read write state in a stream
5191------------------------------------------------------------------------------
5193-- | Evaluate the inner monad of a stream as 'StateT'.
5195-- This is supported only for 'SerialT' as concurrent state updation may not be
5200{-# INLINE evalStateT #-}
5201evalStateT :: Monad m => m s -> SerialT (StateT s m) a -> SerialT m a
5202evalStateT s xs = fromStreamD $ D.evalStateT s (toStreamD xs)
5204-- | Run a stateful (StateT) stream transformation using a given state.
5206-- This is supported only for 'SerialT' as concurrent state updation may not be
5209-- See also: 'scanl''
5213{-# INLINE usingStateT #-}
5217 -> (SerialT (StateT s m) a -> SerialT (StateT s m) a)
5220usingStateT s f xs = evalStateT s $ f $ liftInner xs
5222-- | Evaluate the inner monad of a stream as 'StateT' and emit the resulting
5223-- state and value pair after each step.
5225-- This is supported only for 'SerialT' as concurrent state updation may not be
5230{-# INLINE runStateT #-}
5231runStateT :: Monad m => m s -> SerialT (StateT s m) a -> SerialT m (s, a)
5232runStateT s xs = fromStreamD $ D.runStateT s (toStreamD xs)
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list