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 fold function.
2207{-# INLINE scanlM' #-}
2208scanlM' :: (IsStream t, Monad m) => (b -> a -> m b) -> b -> t m a -> t m b
2209scanlM' step begin m = fromStreamD $ D.scanlM' step begin $ toStreamD m
2211-- | @scanlMAfter' accumulate initial done stream@ is like 'scanlM'' except
2212-- that it provides an additional @done@ function to be applied on the
2213-- accumulator when the stream stops. The result of @done@ is also emitted in
2216-- This function can be used to allocate a resource in the beginning of the
2217-- scan and release it when the stream ends or to flush the internal state of
2218-- the scan at the end.
2222{-# INLINE scanlMAfter' #-}
2223scanlMAfter' :: (IsStream t, Monad m)
2224 => (b -> a -> m b) -> m b -> (b -> m b) -> t m a -> t m b
2225scanlMAfter' step initial done stream =
2226 fromStreamD $ D.scanlMAfter' step initial done $ toStreamD stream
2228-- XXX because of the use of D.cons for appending, scanl' has quadratic
2229-- complexity when iterated over a stream. We should use StreamK style scanlM'
2230-- for linear performance on iteration.
2232-- | Strict left scan. Like 'map', 'scanl'' too is a one to one transformation,
2233-- however it adds an extra element.
2236-- > S.toList $ S.scanl' (+) 0 $ fromList [1,2,3,4]
2241-- > S.toList $ S.scanl' (flip (:)) [] $ S.fromList [1,2,3,4]
2242-- [[],[1],[2,1],[3,2,1],[4,3,2,1]]
2245-- The output of 'scanl'' is the initial value of the accumulator followed by
2246-- all the intermediate steps and the final result of 'foldl''.
2248-- By streaming the accumulated state after each fold step, we can share the
2249-- state across multiple stages of stream composition. Each stage can modify or
2250-- extend the state, do some processing with it and emit it for the next stage,
2251-- thus modularizing the stream processing. This can be useful in
2252-- stateful or event-driven programming.
2254-- Consider the following monolithic example, computing the sum and the product
2255-- of the elements in a stream in one go using a @foldl'@:
2258-- > S.foldl' (\\(s, p) x -> (s + x, p * x)) (0,1) $ S.fromList \[1,2,3,4]
2262-- Using @scanl'@ we can make it modular by computing the sum in the first
2263-- stage and passing it down to the next stage for computing the product:
2266-- > S.foldl' (\\(_, p) (s, x) -> (s, p * x)) (0,1)
2267-- $ S.scanl' (\\(s, _) x -> (s + x, x)) (0,1)
2268-- $ S.fromList \[1,2,3,4]
2272-- IMPORTANT: 'scanl'' evaluates the accumulator to WHNF. To avoid building
2273-- lazy expressions inside the accumulator, it is recommended that a strict
2274-- data structure is used for accumulator.
2276-- See also: 'usingStateT'
2279{-# INLINE scanl' #-}
2280scanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
2281scanl' step z m = fromStreamS $ S.scanl' step z $ toStreamS m
2283-- | Like 'scanl'' but does not stream the initial value of the accumulator.
2285-- > postscanl' f z xs = S.drop 1 $ S.scanl' f z xs
2288{-# INLINE postscanl' #-}
2289postscanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
2290postscanl' step z m = fromStreamD $ D.postscanl' step z $ toStreamD m
2292-- XXX this needs to be concurrent
2293-- | Like 'postscanl'' but with a monadic step function.
2296{-# INLINE postscanlM' #-}
2297postscanlM' :: (IsStream t, Monad m) => (b -> a -> m b) -> b -> t m a -> t m b
2298postscanlM' step z m = fromStreamD $ D.postscanlM' step z $ toStreamD m
2300-- XXX prescanl does not sound very useful, enable only if there is a
2301-- compelling use case.
2303-- | Like scanl' but does not stream the final value of the accumulator.
2306{-# INLINE prescanl' #-}
2307prescanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
2308prescanl' step z m = fromStreamD $ D.prescanl' step z $ toStreamD m
2310-- XXX this needs to be concurrent
2311-- | Like postscanl' but with a monadic step function.
2314{-# INLINE prescanlM' #-}
2315prescanlM' :: (IsStream t, Monad m) => (b -> a -> m b) -> m b -> t m a -> t m b
2316prescanlM' step z m = fromStreamD $ D.prescanlM' step z $ toStreamD m
2318-- XXX this needs to be concurrent
2319-- | Like 'scanl1'' but with a monadic step function.
2322{-# INLINE scanl1M' #-}
2323scanl1M' :: (IsStream t, Monad m) => (a -> a -> m a) -> t m a -> t m a
2324scanl1M' step m = fromStreamD $ D.scanl1M' step $ toStreamD m
2326-- | Like 'scanl'' but for a non-empty stream. The first element of the stream
2327-- is used as the initial value of the accumulator. Does nothing if the stream
2331-- > S.toList $ S.scanl1 (+) $ fromList [1,2,3,4]
2336{-# INLINE scanl1' #-}
2337scanl1' :: (IsStream t, Monad m) => (a -> a -> a) -> t m a -> t m a
2338scanl1' step m = fromStreamD $ D.scanl1' step $ toStreamD m
2340------------------------------------------------------------------------------
2341-- Scanning with a Fold
2342------------------------------------------------------------------------------
2344-- | Scan a stream using the given monadic fold.
2348scan :: (IsStream t, Monad m) => Fold m a b -> t m a -> t m b
2349scan (Fold step begin done) = P.scanlMx' step begin done
2351-- | Postscan a stream using the given monadic fold.
2354{-# INLINE postscan #-}
2355postscan :: (IsStream t, Monad m) => Fold m a b -> t m a -> t m b
2356postscan (Fold step begin done) = P.postscanlMx' step begin done
2358------------------------------------------------------------------------------
2359-- Stateful Transformations
2360------------------------------------------------------------------------------
2362-- XXX this is not a one-to-one map so calling it map may not be right.
2363-- We can perhaps call it zipWithTail or rollWith.
2365-- | Apply a function on every two successive elements of a stream. If the
2366-- stream consists of a single element the output is an empty stream.
2368-- This is the stream equivalent of the list idiom @zipWith f xs (tail xs)@.
2372{-# INLINE rollingMap #-}
2373rollingMap :: (IsStream t, Monad m) => (a -> a -> b) -> t m a -> t m b
2374rollingMap f m = fromStreamD $ D.rollingMap f $ toStreamD m
2376-- | Like 'rollingMap' but with an effectful map function.
2380{-# INLINE rollingMapM #-}
2381rollingMapM :: (IsStream t, Monad m) => (a -> a -> m b) -> t m a -> t m b
2382rollingMapM f m = fromStreamD $ D.rollingMapM f $ toStreamD m
2384------------------------------------------------------------------------------
2385-- Transformation by Filtering
2386------------------------------------------------------------------------------
2388-- | Include only those elements that pass a predicate.
2391{-# INLINE filter #-}
2392#if __GLASGOW_HASKELL__ != 802
2393-- GHC 8.2.2 crashes with this code, when used with "stack"
2394filter :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m a
2395filter p m = fromStreamS $ S.filter p $ toStreamS m
2397filter :: IsStream t => (a -> Bool) -> t m a -> t m a
2401-- | Same as 'filter' but with a monadic predicate.
2404{-# INLINE filterM #-}
2405filterM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
2406filterM p m = fromStreamD $ D.filterM p $ toStreamD m
2408-- | Drop repeated elements that are adjacent to each other.
2412uniq :: (Eq a, IsStream t, Monad m) => t m a -> t m a
2413uniq = fromStreamD . D.uniq . toStreamD
2415-- | Ensures that all the elements of the stream are identical and then returns
2416-- that unique element.
2420the :: (Eq a, Monad m) => SerialT m a -> m (Maybe a)
2421the m = S.the (toStreamS m)
2423-- | Take first 'n' elements from the stream and discard the rest.
2427take :: (IsStream t, Monad m) => Int -> t m a -> t m a
2428take n m = fromStreamS $ S.take n $ toStreamS
2429 (maxYields (Just (fromIntegral n)) m)
2431-- | End the stream as soon as the predicate fails on an element.
2434{-# INLINE takeWhile #-}
2435takeWhile :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m a
2436takeWhile p m = fromStreamS $ S.takeWhile p $ toStreamS m
2438-- | Same as 'takeWhile' but with a monadic predicate.
2441{-# INLINE takeWhileM #-}
2442takeWhileM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
2443takeWhileM p m = fromStreamD $ D.takeWhileM p $ toStreamD m
2445-- | @takeByTime duration@ yields stream elements upto specified time
2446-- @duration@. The duration starts when the stream is evaluated for the first
2447-- time, before the first element is yielded. The time duration is checked
2448-- before generating each element, if the duration has expired the stream
2451-- The total time taken in executing the stream is guaranteed to be /at least/
2452-- @duration@, however, because the duration is checked before generating an
2453-- element, the upper bound is indeterminate and depends on the time taken in
2454-- generating and processing the last element.
2456-- No element is yielded if the duration is zero. At least one element is
2457-- yielded if the duration is non-zero.
2461{-# INLINE takeByTime #-}
2462takeByTime ::(MonadIO m, IsStream t, TimeUnit64 d) => d -> t m a -> t m a
2463takeByTime d = fromStreamD . D.takeByTime d . toStreamD
2465-- | Discard first 'n' elements from the stream and take the rest.
2469drop :: (IsStream t, Monad m) => Int -> t m a -> t m a
2470drop n m = fromStreamS $ S.drop n $ toStreamS m
2472-- | Drop elements in the stream as long as the predicate succeeds and then
2473-- take the rest of the stream.
2476{-# INLINE dropWhile #-}
2477dropWhile :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m a
2478dropWhile p m = fromStreamS $ S.dropWhile p $ toStreamS m
2480-- | Same as 'dropWhile' but with a monadic predicate.
2483{-# INLINE dropWhileM #-}
2484dropWhileM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
2485dropWhileM p m = fromStreamD $ D.dropWhileM p $ toStreamD m
2487-- | @dropByTime duration@ drops stream elements until specified @duration@ has
2488-- passed. The duration begins when the stream is evaluated for the first
2489-- time. The time duration is checked /after/ generating a stream element, the
2490-- element is yielded if the duration has expired otherwise it is dropped.
2492-- The time elapsed before starting to generate the first element is /at most/
2493-- @duration@, however, because the duration expiry is checked after the
2494-- element is generated, the lower bound is indeterminate and depends on the
2495-- time taken in generating an element.
2497-- All elements are yielded if the duration is zero.
2501{-# INLINE dropByTime #-}
2502dropByTime ::(MonadIO m, IsStream t, TimeUnit64 d) => d -> t m a -> t m a
2503dropByTime d = fromStreamD . D.dropByTime d . toStreamD
2505------------------------------------------------------------------------------
2506-- Transformation by Mapping
2507------------------------------------------------------------------------------
2511-- mapM f = sequence . map f
2514-- Apply a monadic function to each element of the stream and replace it with
2515-- the output of the resulting action.
2518-- > drain $ S.mapM putStr $ S.fromList ["a", "b", "c"]
2521-- drain $ S.replicateM 10 (return 1)
2522-- & (serially . S.mapM (\\x -> threadDelay 1000000 >> print x))
2524-- drain $ S.replicateM 10 (return 1)
2525-- & (asyncly . S.mapM (\\x -> threadDelay 1000000 >> print x))
2528-- /Concurrent (do not use with 'parallely' on infinite streams)/
2531{-# INLINE_EARLY mapM #-}
2532mapM :: (IsStream t, MonadAsync m) => (a -> m b) -> t m a -> t m b
2535{-# RULES "mapM serial" mapM = mapMSerial #-}
2536{-# INLINE mapMSerial #-}
2537mapMSerial :: Monad m => (a -> m b) -> SerialT m a -> SerialT m b
2538mapMSerial = Serial.mapM
2542-- sequence = mapM id
2545-- Replace the elements of a stream of monadic actions with the outputs of
2549-- > drain $ S.sequence $ S.fromList [putStr "a", putStr "b", putStrLn "c"]
2552-- drain $ S.replicateM 10 (return $ threadDelay 1000000 >> print 1)
2553-- & (serially . S.sequence)
2555-- drain $ S.replicateM 10 (return $ threadDelay 1000000 >> print 1)
2556-- & (asyncly . S.sequence)
2559-- /Concurrent (do not use with 'parallely' on infinite streams)/
2562{-# INLINE sequence #-}
2563sequence :: (IsStream t, MonadAsync m) => t m (m a) -> t m a
2564sequence m = fromStreamS $ S.sequence (toStreamS m)
2568-- The stateful step function can be simplified to @(s -> a -> m b)@ to provide
2569-- a read-only environment. However, that would just be 'mapM'.
2571-- The initial action could be @m (s, Maybe b)@, and we can also add a final
2572-- action @s -> m (Maybe b)@. This can be used to get pre/post scan like
2573-- functionality and also to flush the state in the end like scanlMAfter'.
2574-- We can also use it along with a fusible version of bracket to get
2575-- scanlMAfter' like functionality. See issue #677.
2577-- This can be further generalized to a type similar to Fold/Parser, giving it
2578-- filtering and parsing capability as well (this is in fact equivalent to
2581-- smapM :: (s -> a -> m (Step s b)) -> m s -> t m a -> t m b
2584-- | A stateful 'mapM', equivalent to a left scan, more like mapAccumL.
2585-- Hopefully, this is a better alternative to @scan@. Separation of state from
2586-- the output makes it easier to think in terms of a shared state, and also
2587-- makes it easier to keep the state fully strict and the output lazy.
2589-- See also: 'scanlM''
2594smapM :: (IsStream t, Monad m) =>
2595 (s -> a -> m (s, b))
2599smapM step initial stream =
2600 -- XXX implement this directly instead of using scanlM'
2601 -- Once we have scanlM' with monadic initial we can use this code
2603 -- (\(s, _) a -> step s a)
2604 -- (fmap (,undefined) initial)
2607 (\s0 -> scanlM' (\(s, _) a -> step s a) (s0, undefined) stream)
2611------------------------------------------------------------------------------
2613------------------------------------------------------------------------------
2615-- | Map a 'Maybe' returning function to a stream, filter out the 'Nothing'
2616-- elements, and return a stream of values extracted from 'Just'.
2621-- mapMaybe f = S.map 'fromJust' . S.filter 'isJust' . S.map f
2625{-# INLINE mapMaybe #-}
2626mapMaybe :: (IsStream t, Monad m) => (a -> Maybe b) -> t m a -> t m b
2627mapMaybe f m = fromStreamS $ S.mapMaybe f $ toStreamS m
2629-- | Like 'mapMaybe' but maps a monadic function.
2634-- mapMaybeM f = S.map 'fromJust' . S.filter 'isJust' . S.mapM f
2637-- /Concurrent (do not use with 'parallely' on infinite streams)/
2640{-# INLINE_EARLY mapMaybeM #-}
2641mapMaybeM :: (IsStream t, MonadAsync m, Functor (t m))
2642 => (a -> m (Maybe b)) -> t m a -> t m b
2643mapMaybeM f = fmap fromJust . filter isJust . K.mapM f
2645{-# RULES "mapMaybeM serial" mapMaybeM = mapMaybeMSerial #-}
2646{-# INLINE mapMaybeMSerial #-}
2647mapMaybeMSerial :: Monad m => (a -> m (Maybe b)) -> SerialT m a -> SerialT m b
2648mapMaybeMSerial f m = fromStreamD $ D.mapMaybeM f $ toStreamD m
2650-- | In a stream of 'Maybe's, discard 'Nothing's and unwrap 'Just's.
2654catMaybes :: (IsStream t, Monad m, Functor (t m)) => t m (Maybe a) -> t m a
2655catMaybes = fmap fromJust . filter isJust
2657------------------------------------------------------------------------------
2658-- Transformation by Reordering
2659------------------------------------------------------------------------------
2661-- XXX Use a compact region list to temporarily store the list, in both reverse
2662-- as well as in reverse'.
2664-- /Note:/ 'reverse'' is much faster than this, use that when performance
2667-- > reverse = S.foldlT (flip S.cons) S.nil
2669-- | Returns the elements of the stream in reverse order. The stream must be
2670-- finite. Note that this necessarily buffers the entire stream in memory.
2672-- /Since 0.7.0 (Monad m constraint)/
2675{-# INLINE reverse #-}
2676reverse :: (IsStream t, Monad m) => t m a -> t m a
2677reverse s = fromStreamS $ S.reverse $ toStreamS s
2679-- | Like 'reverse' but several times faster, requires a 'Storable' instance.
2682{-# INLINE reverse' #-}
2683reverse' :: (IsStream t, MonadIO m, Storable a) => t m a -> t m a
2684reverse' s = fromStreamD $ D.reverse' $ toStreamD s
2686------------------------------------------------------------------------------
2687-- Transformation by Inserting
2688------------------------------------------------------------------------------
2690-- intersperseM = intersperseBySpan 1
2692-- | Insert an effect and its output before consuming an element of a stream
2693-- except the first one.
2696-- >>> S.toList $ S.trace putChar $ S.intersperseM (putChar '.' >> return ',') $ S.fromList "hello"
2697-- > h.,e.,l.,l.,o"h,e,l,l,o"
2701{-# INLINE intersperseM #-}
2702intersperseM :: (IsStream t, MonadAsync m) => m a -> t m a -> t m a
2703intersperseM m = fromStreamS . S.intersperseM m . toStreamS
2705-- | Insert a side effect before consuming an element of a stream except the
2709-- >>> S.drain $ S.trace putChar $ S.intersperseM_ (putChar '.') $ S.fromList "hello"
2714{-# INLINE intersperseM_ #-}
2715intersperseM_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
2716intersperseM_ m = fromStreamD . D.intersperseM_ m . toStreamD
2718-- | Insert a pure value between successive elements of a stream.
2721-- > S.toList $ S.intersperse ',' $ S.fromList "hello"
2726{-# INLINE intersperse #-}
2727intersperse :: (IsStream t, MonadAsync m) => a -> t m a -> t m a
2728intersperse a = fromStreamS . S.intersperse a . toStreamS
2730-- | Insert an effect and its output after consuming an element of a stream.
2733-- >>> S.toList $ S.trace putChar $ S.intersperseSuffix (putChar '.' >> return ',') $ S.fromList "hello"
2734-- > h.,e.,l.,l.,o.,"h,e,l,l,o,"
2738{-# INLINE intersperseSuffix #-}
2739intersperseSuffix :: (IsStream t, MonadAsync m) => m a -> t m a -> t m a
2740intersperseSuffix m = fromStreamD . D.intersperseSuffix m . toStreamD
2742-- | Insert a side effect after consuming an element of a stream.
2745-- > S.mapM_ putChar $ S.intersperseSuffix_ (threadDelay 1000000) $ S.fromList "hello"
2750{-# INLINE intersperseSuffix_ #-}
2751intersperseSuffix_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
2752intersperseSuffix_ m = fromStreamD . D.intersperseSuffix_ m . toStreamD
2754-- | Insert a side effect before consuming an element of a stream.
2757-- >>> S.toList $ S.trace putChar $ S.interspersePrefix_ (putChar '.' >> return ',') $ S.fromList "hello"
2758-- > .h.e.l.l.o"hello"
2761-- See also: 'trace_'
2767{-# INLINE interspersePrefix_ #-}
2768interspersePrefix_ :: (IsStream t, MonadAsync m) => m b -> t m a -> t m a
2769interspersePrefix_ m = mapM (\x -> void m >> return x)
2771-- Note: delay must be serial.
2773-- | Introduce a delay of specified seconds before consuming an element of the
2774-- stream except the first one.
2777-- >>> S.mapM_ print $ S.timestamped $ S.delay 1 $ S.enumerateFromTo 1 3
2778-- > (AbsTime (TimeSpec {sec = 2502706, nsec = 751137000}),1)
2779-- > (AbsTime (TimeSpec {sec = 2502707, nsec = 743535000}),2)
2780-- > (AbsTime (TimeSpec {sec = 2502708, nsec = 749758000}),3)
2786delay :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
2787delay n = intersperseM_ $ liftIO $ threadDelay $ round $ n * 1000000
2789-- Note: delay must be serial.
2791-- | Introduce a delay of specified seconds after consuming an element of a
2795-- >>> S.mapM_ print $ S.timestamped $ S.delayPost 1 $ S.enumerateFromTo 1 3
2796-- > (AbsTime (TimeSpec {sec = 2502826, nsec = 119030000}),1)
2797-- > (AbsTime (TimeSpec {sec = 2502827, nsec = 111393000}),2)
2798-- > (AbsTime (TimeSpec {sec = 2502828, nsec = 112221000}),3)
2803{-# INLINE delayPost #-}
2804delayPost :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
2805delayPost n = intersperseSuffix_ $ liftIO $ threadDelay $ round $ n * 1000000
2807-- Note: delay must be serial, that's why 'trace_' is used.
2809-- | Introduce a delay of specified seconds before consuming an element of a
2813-- >>> S.mapM_ print $ S.timestamped $ S.delayPre 1 $ S.enumerateFromTo 1 3
2814-- > (AbsTime (TimeSpec {sec = 2502207, nsec = 533177000}),1)
2815-- > (AbsTime (TimeSpec {sec = 2502208, nsec = 530859000}),2)
2816-- > (AbsTime (TimeSpec {sec = 2502209, nsec = 531619000}),3)
2821{-# INLINE delayPre #-}
2822delayPre :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
2823delayPre n = trace_ $ liftIO $ threadDelay $ round $ n * 1000000
2825-- | Like 'intersperseSuffix' but intersperses an effectful action into the
2826-- input stream after every @n@ elements and after the last element.
2829-- > S.toList $ S.intersperseSuffixBySpan 2 (return ',') $ S.fromList "hello"
2835{-# INLINE intersperseSuffixBySpan #-}
2836intersperseSuffixBySpan :: (IsStream t, MonadAsync m)
2837 => Int -> m a -> t m a -> t m a
2838intersperseSuffixBySpan n eff =
2839 fromStreamD . D.intersperseSuffixBySpan n eff . toStreamD
2842-- | Intersperse a monadic action into the input stream after every @n@
2846-- > S.toList $ S.intersperseBySpan 2 (return ',') $ S.fromList "hello"
2851{-# INLINE intersperseBySpan #-}
2852intersperseBySpan :: IsStream t => Int -> m a -> t m a -> t m a
2853intersperseBySpan _n _f _xs = undefined
2856-- | Intersperse a monadic action into the input stream after every @n@
2860-- > S.drain $ S.interjectSuffix 1 (putChar ',') $ S.mapM (\\x -> threadDelay 1000000 >> putChar x) $ S.fromList "hello"
2865{-# INLINE interjectSuffix #-}
2867 :: (IsStream t, MonadAsync m)
2868 => Double -> m a -> t m a -> t m a
2869interjectSuffix n f xs = xs `Par.parallelFst` repeatM timed
2870 where timed = liftIO (threadDelay (round $ n * 1000000)) >> f
2872-- | @insertBy cmp elem stream@ inserts @elem@ before the first element in
2873-- @stream@ that is less than @elem@ when compared using @cmp@.
2876-- insertBy cmp x = 'mergeBy' cmp ('yield' x)
2880-- > S.toList $ S.insertBy compare 2 $ S.fromList [1,3,5]
2885{-# INLINE insertBy #-}
2887 (IsStream t, Monad m) => (a -> a -> Ordering) -> a -> t m a -> t m a
2888insertBy cmp x m = fromStreamS $ S.insertBy cmp x (toStreamS m)
2890------------------------------------------------------------------------------
2892------------------------------------------------------------------------------
2894-- | Deletes the first occurrence of the element in the stream that satisfies
2895-- the given equality predicate.
2898-- > S.toList $ S.deleteBy (==) 3 $ S.fromList [1,3,3,5]
2903{-# INLINE deleteBy #-}
2904deleteBy :: (IsStream t, Monad m) => (a -> a -> Bool) -> a -> t m a -> t m a
2905deleteBy cmp x m = fromStreamS $ S.deleteBy cmp x (toStreamS m)
2907------------------------------------------------------------------------------
2909------------------------------------------------------------------------------
2912-- > indexed = S.postscanl' (\(i, _) x -> (i + 1, x)) (-1,undefined)
2913-- > indexed = S.zipWith (,) (S.enumerateFrom 0)
2915-- Pair each element in a stream with its index, starting from index 0.
2918-- > S.toList $ S.indexed $ S.fromList "hello"
2919-- [(0,'h'),(1,'e'),(2,'l'),(3,'l'),(4,'o')]
2923{-# INLINE indexed #-}
2924indexed :: (IsStream t, Monad m) => t m a -> t m (Int, a)
2925indexed = fromStreamD . D.indexed . toStreamD
2928-- > indexedR n = S.postscanl' (\(i, _) x -> (i - 1, x)) (n + 1,undefined)
2929-- > indexedR n = S.zipWith (,) (S.enumerateFromThen n (n - 1))
2931-- Pair each element in a stream with its index, starting from the
2932-- given index @n@ and counting down.
2935-- > S.toList $ S.indexedR 10 $ S.fromList "hello"
2936-- [(10,'h'),(9,'e'),(8,'l'),(7,'l'),(6,'o')]
2940{-# INLINE indexedR #-}
2941indexedR :: (IsStream t, Monad m) => Int -> t m a -> t m (Int, a)
2942indexedR n = fromStreamD . D.indexedR n . toStreamD
2944-- Note: The timestamp stream must be the second stream in the zip so that the
2945-- timestamp is generated after generating the stream element and not before.
2946-- If we do not do that then the following example will generate the same
2947-- timestamp for first two elements:
2949-- S.mapM_ print $ S.timestamped $ S.delay $ S.enumerateFromTo 1 3
2951-- | Pair each element in a stream with an absolute timestamp, using a clock of
2952-- specified granularity. The timestamp is generated just before the element
2956-- >>> S.mapM_ print $ S.timestampWith 0.01 $ S.delay 1 $ S.enumerateFromTo 1 3
2961{-# INLINE timestampWith #-}
2962timestampWith :: (IsStream t, MonadAsync m, Functor (t m))
2963 => Double -> t m a -> t m (AbsTime, a)
2964timestampWith g stream = Z.zipWith (flip (,)) stream (absTimesWith g)
2966-- TBD: check performance vs a custom implementation without using zipWith.
2968-- | Pair each element in a stream with an absolute timestamp, using a clock of
2969-- 10 ms granularity. The timestamp is generated just before the element is
2973-- >>> S.mapM_ print $ S.timestamped $ S.delay 1 $ S.enumerateFromTo 1 3
2974-- (AbsTime (TimeSpec {sec = 2460689, nsec = 641121000}),1)
2975-- (AbsTime (TimeSpec {sec = 2460690, nsec = 639334000}),2)
2976-- (AbsTime (TimeSpec {sec = 2460691, nsec = 644479000}),3)
2981{-# INLINE timestamped #-}
2982timestamped :: (IsStream t, MonadAsync m, Functor (t m))
2983 => t m a -> t m (AbsTime, a)
2984timestamped = timestampWith 0.01
2986-- | Pair each element in a stream with relative times starting from 0, using a
2987-- clock with the specified granularity. The time is measured just before the
2988-- element is consumed.
2991-- >>> S.mapM_ print $ S.timeIndexWith 0.01 $ S.delay 1 $ S.enumerateFromTo 1 3
2996{-# INLINE timeIndexWith #-}
2997timeIndexWith :: (IsStream t, MonadAsync m, Functor (t m))
2998 => Double -> t m a -> t m (RelTime64, a)
2999timeIndexWith g stream = Z.zipWith (flip (,)) stream (relTimesWith g)
3001-- | Pair each element in a stream with relative times starting from 0, using a
3002-- 10 ms granularity clock. The time is measured just before the element is
3006-- >>> S.mapM_ print $ S.timeIndexed $ S.delay 1 $ S.enumerateFromTo 1 3
3007-- (RelTime64 (NanoSecond64 0),1)
3008-- (RelTime64 (NanoSecond64 996239000),2)
3009-- (RelTime64 (NanoSecond64 1996712000),3)
3014{-# INLINE timeIndexed #-}
3015timeIndexed :: (IsStream t, MonadAsync m, Functor (t m))
3016 => t m a -> t m (RelTime64, a)
3017timeIndexed = timeIndexWith 0.01
3019------------------------------------------------------------------------------
3021------------------------------------------------------------------------------
3023-- | Compare two streams for equality using an equality function.
3026{-# INLINABLE eqBy #-}
3027eqBy :: (IsStream t, Monad m) => (a -> b -> Bool) -> t m a -> t m b -> m Bool
3030-- | Compare two streams lexicographically using a comparison function.
3033{-# INLINABLE cmpBy #-}
3035 :: (IsStream t, Monad m)
3036 => (a -> b -> Ordering) -> t m a -> t m b -> m Ordering
3039------------------------------------------------------------------------------
3041------------------------------------------------------------------------------
3043-- | Merge two streams using a comparison function. The head elements of both
3044-- the streams are compared and the smaller of the two elements is emitted, if
3045-- both elements are equal then the element from the first stream is used
3048-- If the streams are sorted in ascending order, the resulting stream would
3049-- also remain sorted in ascending order.
3052-- > S.toList $ S.mergeBy compare (S.fromList [1,3,5]) (S.fromList [2,4,6,8])
3057{-# INLINABLE mergeBy #-}
3059 (IsStream t, Monad m) => (a -> a -> Ordering) -> t m a -> t m a -> t m a
3060mergeBy f m1 m2 = fromStreamS $ S.mergeBy f (toStreamS m1) (toStreamS m2)
3062-- | Like 'mergeBy' but with a monadic comparison function.
3064-- Merge two streams randomly:
3067-- > randomly _ _ = randomIO >>= \x -> return $ if x then LT else GT
3068-- > S.toList $ S.mergeByM randomly (S.fromList [1,1,1,1]) (S.fromList [2,2,2,2])
3072-- Merge two streams in a proportion of 2:1:
3075-- proportionately m n = do
3076-- ref <- newIORef $ cycle $ concat [replicate m LT, replicate n GT]
3077-- return $ \\_ _ -> do
3078-- r <- readIORef ref
3079-- writeIORef ref $ tail r
3083-- f <- proportionately 2 1
3084-- xs <- S.toList $ S.mergeByM f (S.fromList [1,1,1,1,1,1]) (S.fromList [2,2,2])
3088-- [1,1,2,1,1,2,1,1,2]
3092{-# INLINABLE mergeByM #-}
3094 :: (IsStream t, Monad m)
3095 => (a -> a -> m Ordering) -> t m a -> t m a -> t m a
3096mergeByM f m1 m2 = fromStreamS $ S.mergeByM f (toStreamS m1) (toStreamS m2)
3099-- | Like 'mergeByM' but stops merging as soon as any of the two streams stops.
3100{-# INLINABLE mergeEndByAny #-}
3102 :: (IsStream t, Monad m)
3103 => (a -> a -> m Ordering) -> t m a -> t m a -> t m a
3104mergeEndByAny f m1 m2 = fromStreamD $
3105 D.mergeEndByAny f (toStreamD m1) (toStreamD m2)
3107-- Like 'mergeByM' but stops merging as soon as the first stream stops.
3108{-# INLINABLE mergeEndByFirst #-}
3110 :: (IsStream t, Monad m)
3111 => (a -> a -> m Ordering) -> t m a -> t m a -> t m a
3112mergeEndByFirst f m1 m2 = fromStreamS $
3113 D.mergeEndByFirst f (toStreamD m1) (toStreamD m2)
3116-- Holding this back for now, we may want to use the name "merge" differently
3118-- | Same as @'mergeBy' 'compare'@.
3121-- > S.toList $ S.merge (S.fromList [1,3,5]) (S.fromList [2,4,6,8])
3126{-# INLINABLE merge #-}
3128 (IsStream t, Monad m, Ord a) => t m a -> t m a -> t m a
3129merge = mergeBy compare
3132-- | Like 'mergeBy' but merges concurrently (i.e. both the elements being
3133-- merged are generated concurrently).
3136{-# INLINE mergeAsyncBy #-}
3137mergeAsyncBy :: (IsStream t, MonadAsync m)
3138 => (a -> a -> Ordering) -> t m a -> t m a -> t m a
3139mergeAsyncBy f = mergeAsyncByM (\a b -> return $ f a b)
3141-- | Like 'mergeByM' but merges concurrently (i.e. both the elements being
3142-- merged are generated concurrently).
3145{-# INLINE mergeAsyncByM #-}
3146mergeAsyncByM :: (IsStream t, MonadAsync m)
3147 => (a -> a -> m Ordering) -> t m a -> t m a -> t m a
3148mergeAsyncByM f m1 m2 = fromStreamD $
3149 D.mergeByM f (D.mkParallelD $ toStreamD m1) (D.mkParallelD $ toStreamD m2)
3151------------------------------------------------------------------------------
3153------------------------------------------------------------------------------
3155-- | @concatMapWith merge map stream@ is a two dimensional looping combinator.
3156-- The first argument specifies a merge or concat function that is used to
3157-- merge the streams generated by applying the second argument i.e. the @map@
3158-- function to each element of the input stream. The concat function could be
3159-- 'serial', 'parallel', 'async', 'ahead' or any other zip or merge function
3160-- and the second argument could be any stream generation function using a
3163-- /Compare 'foldMapWith'/
3166{-# INLINE concatMapWith #-}
3169 => (t m b -> t m b -> t m b)
3173concatMapWith = K.concatMapBy
3175-- | Like 'concatMapWith' but carries a state which can be used to share
3176-- information across multiple steps of concat.
3179-- concatSmapMWith combine f initial = concatMapWith combine id . smapM f initial
3184{-# INLINE concatSmapMWith #-}
3186 :: (IsStream t, Monad m)
3187 => (t m b -> t m b -> t m b)
3188 -> (s -> a -> m (s, t m b))
3192concatSmapMWith combine f initial = concatMapWith combine id . smapM f initial
3194-- | Map a stream producing function on each element of the stream and then
3195-- flatten the results into a single stream.
3198-- concatMap f = 'concat . map f'
3199-- concatMap = 'concatMapWith' 'Serial.serial'
3200-- concatMap f = 'concatMapM' (return . f)
3201-- concatMap f = 'concatUnfold' (UF.lmap f UF.fromStream)
3205{-# INLINE concatMap #-}
3206concatMap ::(IsStream t, Monad m) => (a -> t m b) -> t m a -> t m b
3207concatMap f m = fromStreamD $ D.concatMap (toStreamD . f) (toStreamD m)
3209-- | Flatten a stream of streams to a single stream.
3212-- concat = concatMap id
3216{-# INLINE concat #-}
3217concat :: (IsStream t, Monad m) => t m (t m a) -> t m a
3218concat = concatMap id
3220-- | Append the outputs of two streams, yielding all the elements from the
3221-- first stream and then yielding all the elements from the second stream.
3223-- IMPORTANT NOTE: This could be 100x faster than @serial/<>@ for appending a
3224-- few (say 100) streams because it can fuse via stream fusion. However, it
3225-- does not scale for a large number of streams (say 1000s) and becomes
3226-- qudartically slow. Therefore use this for custom appending of a few streams
3227-- but use 'concatMap' or 'concatMapWith serial' for appending @n@ streams or
3228-- infinite containers of streams.
3231{-# INLINE append #-}
3232append ::(IsStream t, Monad m) => t m b -> t m b -> t m b
3233append m1 m2 = fromStreamD $ D.append (toStreamD m1) (toStreamD m2)
3235-- XXX Same as 'wSerial'. We should perhaps rename wSerial to interleave.
3236-- XXX Document the interleaving behavior of side effects in all the
3237-- interleaving combinators.
3238-- XXX Write time-domain equivalents of these. In the time domain we can
3239-- interleave two streams such that the value of second stream is always taken
3240-- from its last value even if no new value is being yielded, like
3241-- zipWithLatest. It would be something like interleaveWithLatest.
3243-- | Interleaves the outputs of two streams, yielding elements from each stream
3244-- alternately, starting from the first stream. If any of the streams finishes
3245-- early the other stream continues alone until it too finishes.
3247-- >>> :set -XOverloadedStrings
3248-- >>> interleave "ab" ",,,," :: SerialT Identity Char
3250-- >>> interleave "abcd" ",," :: SerialT Identity Char
3253-- 'interleave' is dual to 'interleaveMin', it can be called @interleaveMax@.
3255-- Do not use at scale in concatMapWith.
3258{-# INLINE interleave #-}
3259interleave ::(IsStream t, Monad m) => t m b -> t m b -> t m b
3260interleave m1 m2 = fromStreamD $ D.interleave (toStreamD m1) (toStreamD m2)
3262-- | Interleaves the outputs of two streams, yielding elements from each stream
3263-- alternately, starting from the first stream. As soon as the first stream
3264-- finishes, the output stops, discarding the remaining part of the second
3265-- stream. In this case, the last element in the resulting stream would be from
3266-- the second stream. If the second stream finishes early then the first stream
3267-- still continues to yield elements until it finishes.
3269-- >>> :set -XOverloadedStrings
3270-- >>> interleaveSuffix "abc" ",,,," :: SerialT Identity Char
3272-- >>> interleaveSuffix "abc" "," :: SerialT Identity Char
3275-- 'interleaveSuffix' is a dual of 'interleaveInfix'.
3277-- Do not use at scale in concatMapWith.
3280{-# INLINE interleaveSuffix #-}
3281interleaveSuffix ::(IsStream t, Monad m) => t m b -> t m b -> t m b
3282interleaveSuffix m1 m2 =
3283 fromStreamD $ D.interleaveSuffix (toStreamD m1) (toStreamD m2)
3285-- | Interleaves the outputs of two streams, yielding elements from each stream
3286-- alternately, starting from the first stream and ending at the first stream.
3287-- If the second stream is longer than the first, elements from the second
3288-- stream are infixed with elements from the first stream. If the first stream
3289-- is longer then it continues yielding elements even after the second stream
3292-- >>> :set -XOverloadedStrings
3293-- >>> interleaveInfix "abc" ",,,," :: SerialT Identity Char
3295-- >>> interleaveInfix "abc" "," :: SerialT Identity Char
3298-- 'interleaveInfix' is a dual of 'interleaveSuffix'.
3300-- Do not use at scale in concatMapWith.
3303{-# INLINE interleaveInfix #-}
3304interleaveInfix ::(IsStream t, Monad m) => t m b -> t m b -> t m b
3305interleaveInfix m1 m2 =
3306 fromStreamD $ D.interleaveInfix (toStreamD m1) (toStreamD m2)
3308-- | Interleaves the outputs of two streams, yielding elements from each stream
3309-- alternately, starting from the first stream. The output stops as soon as any
3310-- of the two streams finishes, discarding the remaining part of the other
3311-- stream. The last element of the resulting stream would be from the longer
3314-- >>> :set -XOverloadedStrings
3315-- >>> interleaveMin "ab" ",,,," :: SerialT Identity Char
3317-- >>> interleaveMin "abcd" ",," :: SerialT Identity Char
3320-- 'interleaveMin' is dual to 'interleave'.
3322-- Do not use at scale in concatMapWith.
3325{-# INLINE interleaveMin #-}
3326interleaveMin ::(IsStream t, Monad m) => t m b -> t m b -> t m b
3327interleaveMin m1 m2 = fromStreamD $ D.interleaveMin (toStreamD m1) (toStreamD m2)
3329-- | Schedule the execution of two streams in a fair round-robin manner,
3330-- executing each stream once, alternately. Execution of a stream may not
3331-- necessarily result in an output, a stream may chose to @Skip@ producing an
3332-- element until later giving the other stream a chance to run. Therefore, this
3333-- combinator fairly interleaves the execution of two streams rather than
3334-- fairly interleaving the output of the two streams. This can be useful in
3335-- co-operative multitasking without using explicit threads. This can be used
3336-- as an alternative to `async`.
3338-- Do not use at scale in concatMapWith.
3341{-# INLINE roundrobin #-}
3342roundrobin ::(IsStream t, Monad m) => t m b -> t m b -> t m b
3343roundrobin m1 m2 = fromStreamD $ D.roundRobin (toStreamD m1) (toStreamD m2)
3345-- | Map a stream producing monadic function on each element of the stream
3346-- and then flatten the results into a single stream. Since the stream
3347-- generation function is monadic, unlike 'concatMap', it can produce an
3348-- effect at the beginning of each iteration of the inner loop.
3351{-# INLINE concatMapM #-}
3352concatMapM :: (IsStream t, Monad m) => (a -> m (t m b)) -> t m a -> t m b
3353concatMapM f m = fromStreamD $ D.concatMapM (fmap toStreamD . f) (toStreamD m)
3355-- | Given a stream value in the underlying monad, lift and join the underlying
3356-- monad with the stream monad.
3359-- concatM = concat . yieldM
3360-- concatM = concat . lift -- requires @(MonadTrans t)@
3361-- concatM = join . lift -- requires @(MonadTrans t@, @Monad (t m))@
3364-- See also: 'concat', 'sequence'
3368{-# INLINE concatM #-}
3369concatM :: (IsStream t, Monad m) => m (t m a) -> t m a
3370concatM generator = concatMapM (\() -> generator) (yield ())
3372-- | Like 'concatMap' but uses an 'Unfold' for stream generation. Unlike
3373-- 'concatMap' this can fuse the 'Unfold' code with the inner loop and
3374-- therefore provide many times better performance.
3377{-# INLINE concatUnfold #-}
3378concatUnfold ::(IsStream t, Monad m) => Unfold m a b -> t m a -> t m b
3379concatUnfold u m = fromStreamD $ D.concatMapU u (toStreamD m)
3381-- | Like 'concatUnfold' but interleaves the streams in the same way as
3382-- 'interleave' behaves instead of appending them.
3385{-# INLINE concatUnfoldInterleave #-}
3386concatUnfoldInterleave ::(IsStream t, Monad m)
3387 => Unfold m a b -> t m a -> t m b
3388concatUnfoldInterleave u m =
3389 fromStreamD $ D.concatUnfoldInterleave u (toStreamD m)
3391-- | Like 'concatUnfold' but executes the streams in the same way as
3395{-# INLINE concatUnfoldRoundrobin #-}
3396concatUnfoldRoundrobin ::(IsStream t, Monad m)
3397 => Unfold m a b -> t m a -> t m b
3398concatUnfoldRoundrobin u m =
3399 fromStreamD $ D.concatUnfoldRoundrobin u (toStreamD m)
3401-- XXX we can swap the order of arguments to gintercalate so that the
3402-- definition of concatUnfold becomes simpler? The first stream should be
3403-- infixed inside the second one. However, if we change the order in
3404-- "interleave" as well similarly, then that will make it a bit unintuitive.
3406-- > concatUnfold unf str =
3407-- > gintercalate unf str (UF.nilM (\_ -> return ())) (repeat ())
3409-- | 'interleaveInfix' followed by unfold and concat.
3412{-# INLINE gintercalate #-}
3414 :: (IsStream t, Monad m)
3415 => Unfold m a c -> t m a -> Unfold m b c -> t m b -> t m c
3416gintercalate unf1 str1 unf2 str2 =
3417 D.fromStreamD $ D.gintercalate
3418 unf1 (D.toStreamD str1)
3419 unf2 (D.toStreamD str2)
3421-- XXX The order of arguments in "intercalate" is consistent with the list
3422-- intercalate but inconsistent with gintercalate and other stream interleaving
3423-- combinators. We can change the order of the arguments in other combinators
3424-- but then 'interleave' combinator may become a bit unintuitive because we
3425-- will be starting with the second stream.
3427-- > intercalate seed unf str = gintercalate unf str unf (repeatM seed)
3428-- > intercalate a unf str = concatUnfold unf $ intersperse a str
3430-- | 'intersperse' followed by unfold and concat.
3432-- > unwords = intercalate " " UF.fromList
3434-- >>> intercalate " " UF.fromList ["abc", "def", "ghi"]
3438{-# INLINE intercalate #-}
3439intercalate :: (IsStream t, Monad m)
3440 => b -> Unfold m b c -> t m b -> t m c
3441intercalate seed unf str = D.fromStreamD $
3442 D.concatMapU unf $ D.intersperse seed (toStreamD str)
3444-- > interpose x unf str = gintercalate unf str UF.identity (repeat x)
3446-- | Unfold the elements of a stream, intersperse the given element between the
3447-- unfolded streams and then concat them into a single stream.
3449-- > unwords = S.interpose ' '
3452{-# INLINE interpose #-}
3453interpose :: (IsStream t, Monad m)
3454 => c -> Unfold m b c -> t m b -> t m c
3455interpose x unf str =
3456 D.fromStreamD $ D.interpose (return x) unf (D.toStreamD str)
3458-- | 'interleaveSuffix' followed by unfold and concat.
3461{-# INLINE gintercalateSuffix #-}
3463 :: (IsStream t, Monad m)
3464 => Unfold m a c -> t m a -> Unfold m b c -> t m b -> t m c
3465gintercalateSuffix unf1 str1 unf2 str2 =
3466 D.fromStreamD $ D.gintercalateSuffix
3467 unf1 (D.toStreamD str1)
3468 unf2 (D.toStreamD str2)
3470-- > intercalateSuffix seed unf str = gintercalateSuffix unf str unf (repeatM seed)
3471-- > intercalateSuffix a unf str = concatUnfold unf $ intersperseSuffix a str
3473-- | 'intersperseSuffix' followed by unfold and concat.
3475-- > unlines = intercalateSuffix "\n" UF.fromList
3477-- >>> intercalate "\n" UF.fromList ["abc", "def", "ghi"]
3478-- > "abc\ndef\nghi\n"
3481{-# INLINE intercalateSuffix #-}
3482intercalateSuffix :: (IsStream t, Monad m)
3483 => b -> Unfold m b c -> t m b -> t m c
3484intercalateSuffix seed unf str = fromStreamD $ D.concatMapU unf
3485 $ D.intersperseSuffix (return seed) (D.toStreamD str)
3487-- interposeSuffix x unf str = gintercalateSuffix unf str UF.identity (repeat x)
3489-- | Unfold the elements of a stream, append the given element after each
3490-- unfolded stream and then concat them into a single stream.
3492-- > unlines = S.interposeSuffix '\n'
3495{-# INLINE interposeSuffix #-}
3496interposeSuffix :: (IsStream t, Monad m)
3497 => c -> Unfold m b c -> t m b -> t m c
3498interposeSuffix x unf str =
3499 D.fromStreamD $ D.interposeSuffix (return x) unf (D.toStreamD str)
3501------------------------------------------------------------------------------
3503------------------------------------------------------------------------------
3505-- | Like 'iterateM' but iterates after mapping a stream generator on the
3508-- Yield an input element in the output stream, map a stream generator on it
3509-- and then do the same on the resulting stream. This can be used for a depth
3510-- first traversal of a tree like structure.
3512-- Note that 'iterateM' is a special case of 'iterateMapWith':
3515-- iterateM f = iterateMapWith serial (yieldM . f) . yieldM
3518-- It can be used to traverse a tree structure. For example, to list a
3522-- Stream.iterateMapWith Stream.serial
3523-- (either Dir.toEither (const nil))
3524-- (yield (Left "tmp"))
3529{-# INLINE iterateMapWith #-}
3532 => (t m a -> t m a -> t m a)
3536iterateMapWith combine f = concatMapWith combine go
3538 go x = yield x `combine` concatMapWith combine go (f x)
3541{-# INLINE iterateUnfold #-}
3542iterateUnfold :: (IsStream t, MonadAsync m)
3543 => Unfold m a a -> t m a -> t m a
3544iterateUnfold unf xs = undefined
3547------------------------------------------------------------------------------
3549------------------------------------------------------------------------------
3551-- To traverse graphs we need a state to be carried around in the traversal.
3552-- For example, we can use a hashmap to store the visited status of nodes.
3554-- | Like 'iterateMap' but carries a state in the stream generation function.
3555-- This can be used to traverse graph like structures, we can remember the
3556-- visited nodes in the state to avoid cycles.
3558-- Note that a combination of 'iterateMap' and 'usingState' can also be used to
3559-- traverse graphs. However, this function provides a more localized state
3560-- instead of using a global state.
3566{-# INLINE iterateSmapMWith #-}
3568 :: (IsStream t, Monad m)
3569 => (t m a -> t m a -> t m a)
3570 -> (b -> a -> m (b, t m a))
3574iterateSmapMWith combine f initial stream =
3575 concatMap (\b -> concatMapWith combine (go b) stream) (yieldM initial)
3579 go b a = yield a `combine` feedback b a
3583 (\(b1, s) -> concatMapWith combine (go b1) s)
3586------------------------------------------------------------------------------
3588------------------------------------------------------------------------------
3590-- | Discard 'Right's and unwrap 'Left's in an 'Either' stream.
3594lefts :: (IsStream t, Monad m, Functor (t m)) => t m (Either a b) -> t m a
3595lefts = fmap (fromLeft undefined) . filter isLeft
3597-- | Discard 'Left's and unwrap 'Right's in an 'Either' stream.
3601rights :: (IsStream t, Monad m, Functor (t m)) => t m (Either a b) -> t m b
3602rights = fmap (fromRight undefined) . filter isRight
3604-- | In an 'Either' stream iterate on 'Left's. This is a special case of
3608-- iterateMapLeftsWith combine f = iterateMapWith combine (either f (const nil))
3611-- To traverse a directory tree:
3614-- iterateMapLeftsWith serial Dir.toEither (yield (Left "tmp"))
3619{-# INLINE iterateMapLeftsWith #-}
3622 => (t m (Either a b) -> t m (Either a b) -> t m (Either a b))
3623 -> (a -> t m (Either a b))
3626iterateMapLeftsWith combine f = iterateMapWith combine (either f (const K.nil))
3628------------------------------------------------------------------------------
3630------------------------------------------------------------------------------
3632-- Splitting operations that take a predicate and a Fold can be
3633-- expressed using parseMany. Operations like chunksOf, intervalsOf, split*,
3634-- can be expressed using parseMany when used with an appropriate Parser.
3636-- XXX We need takeGE/takeBetween to implement "some" using "many".
3638-- | Apply a 'Parser' repeatedly on a stream and emit the parsed values in the
3641-- This is the streaming equivalent of the 'Streamly.Internal.Data.Parser.many'
3644-- >>> S.toList $ S.parseMany (PR.take 2 $ PR.fromFold FL.sum) $ S.fromList [1..10]
3647-- >>> S.toList $ S.parseMany (PR.line FL.toList) $ S.fromList "hello\nworld"
3648-- > ["hello\n","world"]
3652{-# INLINE parseMany #-}
3654 :: (IsStream t, MonadThrow m)
3659 D.fromStreamD $ D.parseMany (PRK.fromParserK p) (D.toStreamD m)
3661{-# INLINE parseManyD #-}
3663 :: (IsStream t, MonadThrow m)
3668 D.fromStreamD $ D.parseMany p (D.toStreamD m)
3670-- | @parseManyTill collect test stream@ tries the parser @test@ on the input,
3671-- if @test@ fails it backtracks and tries @collect@, after @collect@ succeeds
3672-- @test@ is tried again and so on. The parser stops when @test@ succeeds. The
3673-- output of @test@ is discarded and the output of @collect@ is emitted in the
3674-- output stream. The parser fails if @collect@ fails.
3678{-# INLINE parseManyTill #-}
3680 -- (IsStream t, MonadThrow m) =>
3685parseManyTill = undefined
3687-- | Iterate a parser generating function on a stream. The initial value @b@ is
3688-- used to generate the first parser, the parser is applied on the stream and
3689-- the result is used to generate the next parser and so on.
3691-- >>> S.toList $ S.map getSum $ S.parseIterate (\b -> PR.take 2 (FL.mconcatTo b)) 0 $ S.map Sum $ S.fromList [1..10]
3692-- > [3,10,21,36,55,55]
3694-- This is the streaming equivalent of monad like sequenced application of
3695-- parsers where next parser is dependent on the previous parser.
3699{-# INLINE parseIterate #-}
3701 :: (IsStream t, MonadThrow m)
3702 => (b -> Parser m a b)
3706parseIterate f i m = D.fromStreamD $
3707 D.parseIterate (PRK.fromParserK . f) i (D.toStreamD m)
3709------------------------------------------------------------------------------
3710-- Grouping/Splitting
3711------------------------------------------------------------------------------
3713------------------------------------------------------------------------------
3714-- Grouping without looking at elements
3715------------------------------------------------------------------------------
3717------------------------------------------------------------------------------
3719------------------------------------------------------------------------------
3722------------------------------------------------------------------------------
3724------------------------------------------------------------------------------
3726------------------------------------------------------------------------------
3727-- Generalized grouping
3728------------------------------------------------------------------------------
3730-- This combinator is the most general grouping combinator and can be used to
3731-- implement all other grouping combinators.
3733-- XXX check if this can implement the splitOn combinator i.e. we can slide in
3734-- new elements, slide out old elements and incrementally compute the hash.
3735-- Also, can we implement the windowed classification combinators using this?
3737-- In fact this is a parse. Instead of using a special return value in the fold
3738-- we are using a mapping function.
3740-- Note that 'scanl'' (usually followed by a map to extract the desired value
3741-- from the accumulator) can be used to realize many implementations e.g. a
3742-- sliding window implementation. A scan followed by a mapMaybe is also a good
3743-- pattern to express many problems where we want to emit a filtered output and
3744-- not emit an output on every input.
3746-- Passing on of the initial accumulator value to the next fold is equivalent
3747-- to returning the leftover concept.
3750-- | @groupScan splitter fold stream@ folds the input stream using @fold@.
3751-- @splitter@ is applied on the accumulator of the fold every time an item is
3752-- consumed by the fold. The fold continues until @splitter@ returns a 'Just'
3753-- value. A 'Just' result from the @splitter@ specifies a result to be emitted
3754-- in the output stream and the initial value of the accumulator for the next
3755-- group's fold. This allows us to control whether to start fresh for the next
3756-- fold or to continue from the previous fold's output.
3758{-# INLINE groupScan #-}
3760 :: (IsStream t, Monad m)
3761 => (x -> m (Maybe (b, x))) -> Fold m a x -> t m a -> t m b
3762groupScan split fold m = undefined
3765-- | Group the input stream into groups of @n@ elements each and then fold each
3766-- group using the provided fold function.
3768-- >> S.toList $ S.chunksOf 2 FL.sum (S.enumerateFromTo 1 10)
3771-- This can be considered as an n-fold version of 'ltake' where we apply
3772-- 'ltake' repeatedly on the leftover stream until the stream exhausts.
3775{-# INLINE chunksOf #-}
3777 :: (IsStream t, Monad m)
3778 => Int -> Fold m a b -> t m a -> t m b
3779chunksOf n f m = D.fromStreamD $ D.groupsOf n f (D.toStreamD m)
3784{-# INLINE chunksOf2 #-}
3786 :: (IsStream t, Monad m)
3787 => Int -> m c -> Fold2 m c a b -> t m a -> t m b
3788chunksOf2 n action f m = D.fromStreamD $ D.groupsOf2 n action f (D.toStreamD m)
3790-- | @arraysOf n stream@ groups the elements in the input stream into arrays of
3791-- @n@ elements each.
3793-- Same as the following but may be more efficient:
3795-- > arraysOf n = S.chunksOf n (A.writeN n)
3798{-# INLINE arraysOf #-}
3799arraysOf :: (IsStream t, MonadIO m, Storable a)
3800 => Int -> t m a -> t m (Array a)
3801arraysOf n = chunksOf n (writeNUnsafe n)
3803-- XXX we can implement this by repeatedly applying the 'lrunFor' fold.
3804-- XXX add this example after fixing the serial stream rate control
3805-- >>> S.toList $ S.take 5 $ intervalsOf 1 FL.sum $ constRate 2 $ S.enumerateFrom 1
3808-- | Group the input stream into windows of @n@ second each and then fold each
3809-- group using the provided fold function.
3812{-# INLINE intervalsOf #-}
3814 :: (IsStream t, MonadAsync m)
3815 => Double -> Fold m a b -> t m a -> t m b
3817 splitWithSuffix isNothing (FL.lcatMaybes f)
3818 (interjectSuffix n (return Nothing) (Serial.map Just xs))
3820------------------------------------------------------------------------------
3822------------------------------------------------------------------------------
3824-- | @groupsBy cmp f $ S.fromList [a,b,c,...]@ assigns the element @a@ to the
3825-- first group, if @b \`cmp` a@ is 'True' then @b@ is also assigned to the same
3826-- group. If @c \`cmp` a@ is 'True' then @c@ is also assigned to the same
3827-- group and so on. When the comparison fails a new group is started. Each
3828-- group is folded using the fold @f@ and the result of the fold is emitted in
3829-- the output stream.
3831-- >>> S.toList $ S.groupsBy (>) FL.toList $ S.fromList [1,3,7,0,2,5]
3832-- > [[1,3,7],[0,2,5]]
3835{-# INLINE groupsBy #-}
3837 :: (IsStream t, Monad m)
3842groupsBy cmp f m = D.fromStreamD $ D.groupsBy cmp f (D.toStreamD m)
3844-- | Unlike @groupsBy@ this function performs a rolling comparison of two
3845-- successive elements in the input stream. @groupsByRolling cmp f $ S.fromList
3846-- [a,b,c,...]@ assigns the element @a@ to the first group, if @a \`cmp` b@ is
3847-- 'True' then @b@ is also assigned to the same group. If @b \`cmp` c@ is
3848-- 'True' then @c@ is also assigned to the same group and so on. When the
3849-- comparison fails a new group is started. Each group is folded using the fold
3852-- >>> S.toList $ S.groupsByRolling (\a b -> a + 1 == b) FL.toList $ S.fromList [1,2,3,7,8,9]
3853-- > [[1,2,3],[7,8,9]]
3856{-# INLINE groupsByRolling #-}
3858 :: (IsStream t, Monad m)
3863groupsByRolling cmp f m = D.fromStreamD $ D.groupsRollingBy cmp f (D.toStreamD m)
3866-- > groups = groupsBy (==)
3867-- > groups = groupsByRolling (==)
3869-- Groups contiguous spans of equal elements together in individual groups.
3871-- >>> S.toList $ S.groups FL.toList $ S.fromList [1,1,2,2]
3875groups :: (IsStream t, Monad m, Eq a) => Fold m a b -> t m a -> t m b
3876groups = groupsBy (==)
3878------------------------------------------------------------------------------
3879-- N-ary split on a predicate
3880------------------------------------------------------------------------------
3882-- TODO: Use a Splitter configuration similar to the "split" package to make it
3883-- possible to express all splitting combinations. In general, we can have
3884-- infix/suffix/prefix/condensing of separators, dropping both leading/trailing
3885-- separators. We can have a single split operation taking the splitter config
3888-- | Split on an infixed separator element, dropping the separator. Splits the
3889-- stream on separator elements determined by the supplied predicate, separator
3890-- is considered as infixed between two segments, if one side of the separator
3891-- is missing then it is parsed as an empty stream. The supplied 'Fold' is
3892-- applied on the split segments. With '-' representing non-separator elements
3893-- and '.' as separator, 'splitOn' splits as follows:
3896-- "--.--" => "--" "--"
3901-- @splitOn (== x)@ is an inverse of @intercalate (S.yield x)@
3903-- Let's use the following definition for illustration:
3905-- > splitOn' p xs = S.toList $ S.splitOn p (FL.toList) (S.fromList xs)
3907-- >>> splitOn' (== '.') ""
3910-- >>> splitOn' (== '.') "."
3913-- >>> splitOn' (== '.') ".a"
3916-- >>> splitOn' (== '.') "a."
3919-- >>> splitOn' (== '.') "a.b"
3922-- >>> splitOn' (== '.') "a..b"
3927-- This can be considered as an n-fold version of 'breakOn' where we apply
3928-- 'breakOn' successively on the input stream, dropping the first element
3929-- of the second segment after each break.
3931{-# INLINE splitOn #-}
3933 :: (IsStream t, Monad m)
3934 => (a -> Bool) -> Fold m a b -> t m a -> t m b
3935splitOn predicate f m =
3936 D.fromStreamD $ D.splitBy predicate f (D.toStreamD m)
3938-- | Like 'splitOn' but the separator is considered as suffixed to the segments
3939-- in the stream. A missing suffix at the end is allowed. A separator at the
3940-- beginning is parsed as empty segment. With '-' representing elements and
3941-- '.' as separator, 'splitOnSuffix' splits as follows:
3944-- "--.--." => "--" "--"
3945-- "--.--" => "--" "--"
3949-- > splitOnSuffix' p xs = S.toList $ S.splitSuffixBy p (FL.toList) (S.fromList xs)
3951-- >>> splitOnSuffix' (== '.') ""
3954-- >>> splitOnSuffix' (== '.') "."
3957-- >>> splitOnSuffix' (== '.') "a"
3960-- >>> splitOnSuffix' (== '.') ".a"
3963-- >>> splitOnSuffix' (== '.') "a."
3966-- >>> splitOnSuffix' (== '.') "a.b"
3969-- >>> splitOnSuffix' (== '.') "a.b."
3972-- >>> splitOnSuffix' (== '.') "a..b.."
3975-- > lines = splitOnSuffix (== '\n')
3979-- This can be considered as an n-fold version of 'breakPost' where we apply
3980-- 'breakPost' successively on the input stream, dropping the first element
3981-- of the second segment after each break.
3983{-# INLINE splitOnSuffix #-}
3985 :: (IsStream t, Monad m)
3986 => (a -> Bool) -> Fold m a b -> t m a -> t m b
3987splitOnSuffix predicate f m =
3988 D.fromStreamD $ D.splitSuffixBy predicate f (D.toStreamD m)
3990-- | Like 'splitOn' after stripping leading, trailing, and repeated separators.
3991-- Therefore, @".a..b."@ with '.' as the separator would be parsed as
3992-- @["a","b"]@. In other words, its like parsing words from whitespace
3995-- > wordsBy' p xs = S.toList $ S.wordsBy p (FL.toList) (S.fromList xs)
3997-- >>> wordsBy' (== ',') ""
4000-- >>> wordsBy' (== ',') ","
4003-- >>> wordsBy' (== ',') ",a,,b,"
4006-- > words = wordsBy isSpace
4010-- It is equivalent to splitting in any of the infix/prefix/suffix styles
4011-- followed by removal of empty segments.
4012{-# INLINE wordsBy #-}
4014 :: (IsStream t, Monad m)
4015 => (a -> Bool) -> Fold m a b -> t m a -> t m b
4016wordsBy predicate f m =
4017 D.fromStreamD $ D.wordsBy predicate f (D.toStreamD m)
4019-- | Like 'splitOnSuffix' but keeps the suffix attached to the resulting
4022-- > splitWithSuffix' p xs = S.toList $ S.splitWithSuffix p (FL.toList) (S.fromList xs)
4024-- >>> splitWithSuffix' (== '.') ""
4027-- >>> splitWithSuffix' (== '.') "."
4030-- >>> splitWithSuffix' (== '.') "a"
4033-- >>> splitWithSuffix' (== '.') ".a"
4036-- >>> splitWithSuffix' (== '.') "a."
4039-- >>> splitWithSuffix' (== '.') "a.b"
4042-- >>> splitWithSuffix' (== '.') "a.b."
4045-- >>> splitWithSuffix' (== '.') "a..b.."
4046-- > ["a.",".","b.","."]
4050-- This can be considered as an n-fold version of 'breakPost' where we apply
4051-- 'breakPost' successively on the input stream.
4053{-# INLINE splitWithSuffix #-}
4055 :: (IsStream t, Monad m)
4056 => (a -> Bool) -> Fold m a b -> t m a -> t m b
4057splitWithSuffix predicate f m =
4058 D.fromStreamD $ D.splitSuffixBy' predicate f (D.toStreamD m)
4060------------------------------------------------------------------------------
4061-- Split on a delimiter sequence
4062------------------------------------------------------------------------------
4064-- Int list examples for splitOn:
4066-- >>> splitList [] [1,2,3,3,4]
4067-- > [[1],[2],[3],[3],[4]]
4069-- >>> splitList [5] [1,2,3,3,4]
4072-- >>> splitList [1] [1,2,3,3,4]
4075-- >>> splitList [4] [1,2,3,3,4]
4078-- >>> splitList [2] [1,2,3,3,4]
4081-- >>> splitList [3] [1,2,3,3,4]
4084-- >>> splitList [3,3] [1,2,3,3,4]
4087-- >>> splitList [1,2,3,3,4] [1,2,3,3,4]
4090-- | Like 'splitOn' but the separator is a sequence of elements instead of a
4093-- For illustration, let's define a function that operates on pure lists:
4096-- splitOnSeq' pat xs = S.toList $ S.splitOnSeq (A.fromList pat) (FL.toList) (S.fromList xs)
4099-- >>> splitOnSeq' "" "hello"
4100-- > ["h","e","l","l","o"]
4102-- >>> splitOnSeq' "hello" ""
4105-- >>> splitOnSeq' "hello" "hello"
4108-- >>> splitOnSeq' "x" "hello"
4111-- >>> splitOnSeq' "h" "hello"
4114-- >>> splitOnSeq' "o" "hello"
4117-- >>> splitOnSeq' "e" "hello"
4120-- >>> splitOnSeq' "l" "hello"
4123-- >>> splitOnSeq' "ll" "hello"
4126-- 'splitOnSeq' is an inverse of 'intercalate'. The following law always holds:
4128-- > intercalate . splitOn == id
4130-- The following law holds when the separator is non-empty and contains none of
4131-- the elements present in the input lists:
4133-- > splitOn . intercalate == id
4137-- XXX We can use a polymorphic vector implemented by Array# to represent the
4138-- sequence, that way we can avoid the Storable constraint. If we still need
4139-- Storable Array for performance, we can use a separate splitOnArray API for
4140-- that. We can also have an API where the sequence itself is a lazy stream, so
4141-- that we can search files in files for example.
4142{-# INLINE splitOnSeq #-}
4144 :: (IsStream t, MonadIO m, Storable a, Enum a, Eq a)
4145 => Array a -> Fold m a b -> t m a -> t m b
4146splitOnSeq patt f m = D.fromStreamD $ D.splitOn patt f (D.toStreamD m)
4149-- This can be implemented easily using Rabin Karp
4150-- | Split on any one of the given patterns.
4151{-# INLINE splitOnAny #-}
4153 :: (IsStream t, Monad m, Storable a, Integral a)
4154 => [Array a] -> Fold m a b -> t m a -> t m b
4155splitOnAny subseq f m = undefined -- D.fromStreamD $ D.splitOnAny f subseq (D.toStreamD m)
4158-- | Like 'splitSuffixBy' but the separator is a sequence of elements, instead
4159-- of a predicate for a single element.
4161-- > splitSuffixOn_ pat xs = S.toList $ S.splitSuffixOn (A.fromList pat) (FL.toList) (S.fromList xs)
4163-- >>> splitSuffixOn_ "." ""
4166-- >>> splitSuffixOn_ "." "."
4169-- >>> splitSuffixOn_ "." "a"
4172-- >>> splitSuffixOn_ "." ".a"
4175-- >>> splitSuffixOn_ "." "a."
4178-- >>> splitSuffixOn_ "." "a.b"
4181-- >>> splitSuffixOn_ "." "a.b."
4184-- >>> splitSuffixOn_ "." "a..b.."
4187-- > lines = splitSuffixOn "\n"
4190{-# INLINE splitOnSuffixSeq #-}
4192 :: (IsStream t, MonadIO m, Storable a, Enum a, Eq a)
4193 => Array a -> Fold m a b -> t m a -> t m b
4194splitOnSuffixSeq patt f m =
4195 D.fromStreamD $ D.splitSuffixOn False patt f (D.toStreamD m)
4198-- | Like 'splitOn' but drops any empty splits.
4200{-# INLINE wordsOn #-}
4202 :: (IsStream t, Monad m, Storable a, Eq a)
4203 => Array a -> Fold m a b -> t m a -> t m b
4204wordsOn subseq f m = undefined -- D.fromStreamD $ D.wordsOn f subseq (D.toStreamD m)
4207-- XXX use a non-monadic intersperse to remove the MonadAsync constraint.
4209-- | Like 'splitOnSeq' but splits the separator as well, as an infix token.
4211-- > splitOn'_ pat xs = S.toList $ S.splitOn' (A.fromList pat) (FL.toList) (S.fromList xs)
4213-- >>> splitOn'_ "" "hello"
4214-- > ["h","","e","","l","","l","","o"]
4216-- >>> splitOn'_ "hello" ""
4219-- >>> splitOn'_ "hello" "hello"
4222-- >>> splitOn'_ "x" "hello"
4225-- >>> splitOn'_ "h" "hello"
4228-- >>> splitOn'_ "o" "hello"
4231-- >>> splitOn'_ "e" "hello"
4234-- >>> splitOn'_ "l" "hello"
4235-- > ["he","l","","l","o"]
4237-- >>> splitOn'_ "ll" "hello"
4241{-# INLINE splitBySeq #-}
4243 :: (IsStream t, MonadAsync m, Storable a, Enum a, Eq a)
4244 => Array a -> Fold m a b -> t m a -> t m b
4245splitBySeq patt f m =
4246 intersperseM (fold f (A.toStream patt)) $ splitOnSeq patt f m
4248-- | Like 'splitSuffixOn' but keeps the suffix intact in the splits.
4250-- > splitSuffixOn'_ pat xs = S.toList $ FL.splitSuffixOn' (A.fromList pat) (FL.toList) (S.fromList xs)
4252-- >>> splitSuffixOn'_ "." ""
4255-- >>> splitSuffixOn'_ "." "."
4258-- >>> splitSuffixOn'_ "." "a"
4261-- >>> splitSuffixOn'_ "." ".a"
4264-- >>> splitSuffixOn'_ "." "a."
4267-- >>> splitSuffixOn'_ "." "a.b"
4270-- >>> splitSuffixOn'_ "." "a.b."
4273-- >>> splitSuffixOn'_ "." "a..b.."
4274-- > ["a.",".","b.","."]
4277{-# INLINE splitWithSuffixSeq #-}
4279 :: (IsStream t, MonadIO m, Storable a, Enum a, Eq a)
4280 => Array a -> Fold m a b -> t m a -> t m b
4281splitWithSuffixSeq patt f m =
4282 D.fromStreamD $ D.splitSuffixOn True patt f (D.toStreamD m)
4285-- This can be implemented easily using Rabin Karp
4286-- | Split post any one of the given patterns.
4287{-# INLINE splitSuffixOnAny #-}
4289 :: (IsStream t, Monad m, Storable a, Integral a)
4290 => [Array a] -> Fold m a b -> t m a -> t m b
4291splitSuffixOnAny subseq f m = undefined
4292 -- D.fromStreamD $ D.splitPostAny f subseq (D.toStreamD m)
4295------------------------------------------------------------------------------
4297------------------------------------------------------------------------------
4299-- | @splitInnerBy splitter joiner stream@ splits the inner containers @f a@ of
4300-- an input stream @t m (f a)@ using the @splitter@ function. Container
4301-- elements @f a@ are collected until a split occurs, then all the elements
4302-- before the split are joined using the @joiner@ function.
4304-- For example, if we have a stream of @Array Word8@, we may want to split the
4305-- stream into arrays representing lines separated by '\n' byte such that the
4306-- resulting stream after a split would be one array for each line.
4308-- CAUTION! This is not a true streaming function as the container size after
4309-- the split and merge may not be bounded.
4312{-# INLINE splitInnerBy #-}
4314 :: (IsStream t, Monad m)
4315 => (f a -> m (f a, Maybe (f a))) -- splitter
4316 -> (f a -> f a -> m (f a)) -- joiner
4319splitInnerBy splitter joiner xs =
4320 D.fromStreamD $ D.splitInnerBy splitter joiner $ D.toStreamD xs
4322-- | Like 'splitInnerBy' but splits assuming the separator joins the segment in
4326{-# INLINE splitInnerBySuffix #-}
4328 :: (IsStream t, Monad m, Eq (f a), Monoid (f a))
4329 => (f a -> m (f a, Maybe (f a))) -- splitter
4330 -> (f a -> f a -> m (f a)) -- joiner
4333splitInnerBySuffix splitter joiner xs =
4334 D.fromStreamD $ D.splitInnerBySuffix splitter joiner $ D.toStreamD xs
4336------------------------------------------------------------------------------
4337-- Reorder in sequence
4338------------------------------------------------------------------------------
4341-- Buffer until the next element in sequence arrives. The function argument
4342-- determines the difference in sequence numbers. This could be useful in
4343-- implementing sequenced streams, for example, TCP reassembly.
4344{-# INLINE reassembleBy #-}
4346 :: (IsStream t, Monad m)
4351reassembleBy = undefined
4354------------------------------------------------------------------------------
4356------------------------------------------------------------------------------
4358-- | Tap the data flowing through a stream into a 'Fold'. For example, you may
4359-- add a tap to log the contents flowing through the stream. The fold is used
4360-- only for effects, its result is discarded.
4365-- -----stream m a ---------------stream m a-----
4370-- > S.drain $ S.tap (FL.drainBy print) (S.enumerateFromTo 1 2)
4375-- Compare with 'trace'.
4379tap :: (IsStream t, Monad m) => FL.Fold m a b -> t m a -> t m a
4380tap f xs = D.fromStreamD $ D.tap f (D.toStreamD xs)
4382-- | @tapOffsetEvery offset n@ taps every @n@th element in the stream
4383-- starting at @offset@. @offset@ can be between @0@ and @n - 1@. Offset 0
4384-- means start at the first element in the stream. If the offset is outside
4385-- this range then @offset `mod` n@ is used as offset.
4388-- >>> S.drain $ S.tapOffsetEvery 0 2 (FL.mapM print FL.toList) $ S.enumerateFromTo 0 10
4394{-# INLINE tapOffsetEvery #-}
4395tapOffsetEvery :: (IsStream t, Monad m)
4396 => Int -> Int -> FL.Fold m a b -> t m a -> t m a
4397tapOffsetEvery offset n f xs =
4398 D.fromStreamD $ D.tapOffsetEvery offset n f (D.toStreamD xs)
4400-- | Redirect a copy of the stream to a supplied fold and run it concurrently
4401-- in an independent thread. The fold may buffer some elements. The buffer size
4402-- is determined by the prevailing 'maxBuffer' setting.
4407-- -----stream m a ---------------stream m a-----
4412-- > S.drain $ S.tapAsync (S.mapM_ print) (S.enumerateFromTo 1 2)
4417-- Exceptions from the concurrently running fold are propagated to the current
4418-- computation. Note that, because of buffering in the fold, exceptions may be
4419-- delayed and may not correspond to the current element being processed in the
4420-- parent stream, but we guarantee that before the parent stream stops the tap
4421-- finishes and all exceptions from it are drained.
4424-- Compare with 'tap'.
4427{-# INLINE tapAsync #-}
4428tapAsync :: (IsStream t, MonadAsync m) => FL.Fold m a b -> t m a -> t m a
4429tapAsync f xs = D.fromStreamD $ D.tapAsync f (D.toStreamD xs)
4431-- | @pollCounts predicate transform fold stream@ counts those elements in the
4432-- stream that pass the @predicate@. The resulting count stream is sent to
4433-- another thread which transforms it using @transform@ and then folds it using
4434-- @fold@. The thread is automatically cleaned up if the stream stops or
4435-- aborts due to exception.
4437-- For example, to print the count of elements processed every second:
4440-- > S.drain $ S.pollCounts (const True) (S.rollingMap (-) . S.delayPost 1) (FL.drainBy print)
4441-- $ S.enumerateFrom 0
4444-- Note: This may not work correctly on 32-bit machines.
4448{-# INLINE pollCounts #-}
4450 (IsStream t, MonadAsync m)
4452 -> (t m Int -> t m Int)
4456pollCounts predicate transf f xs =
4458 $ D.pollCounts predicate (D.toStreamD . transf . D.fromStreamD) f
4461-- | Calls the supplied function with the number of elements consumed
4462-- every @n@ seconds. The given function is run in a separate thread
4463-- until the end of the stream. In case there is an exception in the
4464-- stream the thread is killed during the next major GC.
4466-- Note: The action is not guaranteed to run if the main thread exits.
4469-- > delay n = threadDelay (round $ n * 1000000) >> return n
4470-- > S.drain $ S.tapRate 2 (\\n -> print $ show n ++ " elements processed") (delay 1 S.|: delay 0.5 S.|: delay 0.5 S.|: S.nil)
4471-- 2 elements processed
4472-- 1 elements processed
4475-- Note: This may not work correctly on 32-bit machines.
4478{-# INLINE tapRate #-}
4480 (IsStream t, MonadAsync m, MonadCatch m)
4485tapRate n f xs = D.fromStreamD $ D.tapRate n f $ D.toStreamD xs
4487-- | Apply a monadic function to each element flowing through the stream and
4488-- discard the results.
4491-- > S.drain $ S.trace print (S.enumerateFromTo 1 2)
4496-- Compare with 'tap'.
4500trace :: (IsStream t, MonadAsync m) => (a -> m b) -> t m a -> t m a
4501trace f = mapM (\x -> void (f x) >> return x)
4503-- | Perform a side effect before yielding each element of the stream and
4504-- discard the results.
4507-- > S.drain $ S.trace_ (print "got here") (S.enumerateFromTo 1 2)
4512-- See also: 'trace', 'interspersePrefix_'
4515{-# INLINE trace_ #-}
4516trace_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
4517trace_ eff = Serial.mapM (\x -> eff >> return x)
4519------------------------------------------------------------------------------
4520-- Windowed classification
4521------------------------------------------------------------------------------
4523-- We divide the stream into windows or chunks in space or time and each window
4524-- can be associated with a key, all events associated with a particular key in
4525-- the window can be folded to a single result. The stream can be split into
4526-- windows by size or by using a split predicate on the elements in the stream.
4527-- For example, when we receive a closing flag, we can close the window.
4529-- A "chunk" is a space window and a "session" is a time window. Are there any
4530-- other better short words to describe them. An alternative is to use
4531-- "swindow" and "twindow". Another word for "session" could be "spell".
4533-- TODO: To mark the position in space or time we can have Indexed or
4534-- TimeStamped types. That can make it easy to deal with the position indices
4537------------------------------------------------------------------------------
4538-- Keyed Sliding Windows
4539------------------------------------------------------------------------------
4542{-# INLINABLE classifySlidingChunks #-}
4543classifySlidingChunks
4544 :: (IsStream t, MonadAsync m, Ord k)
4545 => Int -- ^ window size
4546 -> Int -- ^ window slide
4547 -> Fold m a b -- ^ Fold to be applied to window events
4548 -> t m (k, a, Bool) -- ^ window key, data, close event
4550classifySlidingChunks wsize wslide (Fold step initial extract) str
4553-- XXX Another variant could be to slide the window on an event, e.g. in TCP we
4554-- slide the send window when an ack is received and we slide the receive
4555-- window when a sequence is complete. Sliding is stateful in case of TCP,
4556-- sliding releases the send buffer or makes data available to the user from
4557-- the receive buffer.
4558{-# INLINABLE classifySlidingSessions #-}
4559classifySlidingSessions
4560 :: (IsStream t, MonadAsync m, Ord k)
4561 => Double -- ^ timer tick in seconds
4562 -> Double -- ^ time window size
4563 -> Double -- ^ window slide
4564 -> Fold m a b -- ^ Fold to be applied to window events
4565 -> t m (k, a, Bool, AbsTime) -- ^ window key, data, close flag, timestamp
4567classifySlidingSessions tick interval slide (Fold step initial extract) str
4571------------------------------------------------------------------------------
4572-- Sliding Window Buffers
4573------------------------------------------------------------------------------
4575-- These buffered versions could be faster than concurrent incremental folds of
4576-- all overlapping windows as in many cases we may not need all the values to
4577-- compute the fold, we can just compute the result using the old value and new
4578-- value. However, we may need the buffer once in a while, for example for
4579-- string search we usually compute the hash incrementally but when the hash
4580-- matches the hash of the pattern we need to compare the whole string.
4582-- XXX we should be able to implement sequence based splitting combinators
4583-- using this combinator.
4586-- | Buffer n elements of the input in a ring buffer. When t new elements are
4587-- collected, slide the window to remove the same number of oldest elements,
4588-- insert the new elements, and apply an incremental fold on the sliding
4589-- window, supplying the outgoing elements, the new ring buffer as arguments.
4591 :: (IsStream t, Monad m, Ord a, Storable a)
4592 => Int -- window size
4593 -> Int -- window slide
4594 -> Fold m (Ring a, Array a) b
4597slidingChunkBuffer = undefined
4599-- Buffer n seconds worth of stream elements of the input in a radix tree.
4600-- Every t seconds, remove the items that are older than n seconds, and apply
4601-- an incremental fold on the sliding window, supplying the outgoing elements,
4602-- and the new radix tree buffer as arguments.
4604 :: (IsStream t, Monad m, Ord a, Storable a)
4605 => Int -- window size
4607 -> Fold m (RTree a, Array a) b
4610slidingSessionBuffer = undefined
4613------------------------------------------------------------------------------
4614-- Keyed Session Windows
4615------------------------------------------------------------------------------
4618-- | Keyed variable size space windows. Close the window if we do not receive a
4619-- window event in the next "spaceout" elements.
4620{-# INLINABLE classifyChunksBy #-}
4622 :: (IsStream t, MonadAsync m, Ord k)
4623 => Int -- ^ window spaceout (spread)
4624 -> Bool -- ^ reset the spaceout when a chunk window element is received
4625 -> Fold m a b -- ^ Fold to be applied to chunk window elements
4626 -> t m (k, a, Bool) -- ^ chunk key, data, last element
4628classifyChunksBy spanout reset (Fold step initial extract) str = undefined
4630-- | Like 'classifyChunksOf' but the chunk size is reset if an element is
4631-- received within the chunk size window. The chunk gets closed only if no
4632-- element is received within the chunk window.
4634{-# INLINABLE classifyKeepAliveChunks #-}
4635classifyKeepAliveChunks
4636 :: (IsStream t, MonadAsync m, Ord k)
4637 => Int -- ^ window spaceout (spread)
4638 -> Fold m a b -- ^ Fold to be applied to chunk window elements
4639 -> t m (k, a, Bool) -- ^ chunk key, data, last element
4641classifyKeepAliveChunks spanout = classifyChunksBy spanout True
4644data SessionState t m k a b = SessionState
4645 { sessionCurTime :: !AbsTime -- ^ time since last event
4646 , sessionEventTime :: !AbsTime -- ^ time as per last event
4647 , sessionCount :: !Int -- ^ total number sessions in progress
4648 , sessionTimerHeap :: H.Heap (H.Entry AbsTime k) -- ^ heap for timeouts
4649 , sessionKeyValueMap :: Map.Map k a -- ^ Stored sessions for keys
4650 , sessionOutputStream :: t (m :: Type -> Type) (k, b) -- ^ Completed sessions
4655-- | @classifySessionsBy tick timeout idle pred f stream@ groups timestamped
4656-- events in an input event stream into sessions based on a session key. Each
4657-- element in the stream is an event consisting of a triple @(session key,
4658-- sesssion data, timestamp)@. @session key@ is a key that uniquely identifies
4659-- the session. All the events belonging to a session are folded using the
4660-- fold @f@ until the fold returns a 'Left' result or a timeout has occurred.
4661-- The session key and the result of the fold are emitted in the output stream
4662-- when the session is purged.
4664-- When @idle@ is 'False', @timeout@ is the maximum lifetime of a session in
4665-- seconds, measured from the @timestamp@ of the first event in that session.
4666-- When @idle@ is 'True' then the timeout is an idle timeout, it is reset after
4667-- every event received in the session.
4669-- @timestamp@ in an event characterizes the time when the input event was
4670-- generated, this is an absolute time measured from some @Epoch@. The notion
4671-- of current time is maintained by a monotonic event time clock using the
4672-- timestamps seen in the input stream. The latest timestamp seen till now is
4673-- used as the base for the current time. When no new events are seen, a timer
4674-- is started with a tick duration specified by @tick@. This timer is used to
4675-- detect session timeouts in the absence of new events.
4677-- The predicate @pred@ is invoked with the current session count, if it
4678-- returns 'True' a session is ejected from the session cache before inserting
4679-- a new session. This could be useful to alert or eject sessions when the
4680-- number of sessions becomes too high.
4685-- XXX Perhaps we should use an "Event a" type to represent timestamped data.
4686{-# INLINABLE classifySessionsBy #-}
4688 :: (IsStream t, MonadAsync m, Ord k)
4689 => Double -- ^ timer tick in seconds
4690 -> Double -- ^ session timeout in seconds
4691 -> Bool -- ^ reset the timeout when an event is received
4692 -> (Int -> m Bool) -- ^ predicate to eject sessions based on session count
4693 -> Fold m a (Either b b) -- ^ Fold to be applied to session events
4694 -> t m (k, a, AbsTime) -- ^ session key, data, timestamp
4695 -> t m (k, b) -- ^ session key, fold result
4696classifySessionsBy tick tmout reset ejectPred
4697 (Fold step initial extract) str =
4698 concatMap sessionOutputStream $
4699 scanlMAfter' sstep (return szero) flush stream
4703 timeoutMs = toRelTime (round (tmout * 1000) :: MilliSecond64)
4704 tickMs = toRelTime (round (tick * 1000) :: MilliSecond64)
4705 szero = SessionState
4706 { sessionCurTime = toAbsTime (0 :: MilliSecond64)
4707 , sessionEventTime = toAbsTime (0 :: MilliSecond64)
4709 , sessionTimerHeap = H.empty
4710 , sessionKeyValueMap = Map.empty
4711 , sessionOutputStream = K.nil
4714 -- We can eject sessions based on the current session count to limit
4715 -- memory consumption. There are two possible strategies:
4717 -- 1) Eject old sessions or sessions beyond a certain/lower timeout
4718 -- threshold even before timeout, effectively reduce the timeout.
4719 -- 2) Drop creation of new sessions but keep accepting new events for the
4722 -- We use the first strategy as of now.
4724 -- Got a new stream input element
4725 sstep session@SessionState{..} (Just (key, value, timestamp)) = do
4726 -- XXX we should use a heap in pinned memory to scale it to a large
4729 -- To detect session inactivity we keep a timestamp of the latest event
4730 -- in the Map along with the fold result. When we purge the session
4731 -- from the heap we match the timestamp in the heap with the timestamp
4732 -- in the Map, if the latest timestamp is newer and has not expired we
4733 -- reinsert the key in the heap.
4735 -- XXX if the key is an Int, we can also use an IntMap for slightly
4736 -- better performance.
4738 let curTime = max sessionEventTime timestamp
4742 Just (Tuple' _ acc) -> return acc
4743 new <- step old value
4744 return $ Tuple' timestamp new
4745 mOld = Map.lookup key sessionKeyValueMap
4747 acc@(Tuple' _ fres) <- accumulate mOld
4751 -- deleting a key from the heap is expensive, so we never
4752 -- delete a key from heap, we just purge it from the Map and it
4753 -- gets purged from the heap on timeout. We just need an extra
4754 -- lookup in the Map when the key is purged from the heap, that
4755 -- should not be expensive.
4757 let (mp, cnt) = case mOld of
4758 Nothing -> (sessionKeyValueMap, sessionCount)
4759 Just _ -> (Map.delete key sessionKeyValueMap
4762 { sessionCurTime = curTime
4763 , sessionEventTime = curTime
4764 , sessionCount = cnt
4765 , sessionKeyValueMap = mp
4766 , sessionOutputStream = yield (key, x)
4769 (hp1, mp1, out1, cnt1) <- do
4770 let vars = (sessionTimerHeap, sessionKeyValueMap,
4771 K.nil, sessionCount)
4773 -- inserting new entry
4775 -- Eject a session from heap and map is needed
4776 eject <- ejectPred sessionCount
4777 (hp, mp, out, cnt) <-
4782 -- Insert the new session in heap
4783 let expiry = addToAbsTime timestamp timeoutMs
4784 hp' = H.insert (Entry expiry key) hp
4785 in return (hp', mp, out, cnt + 1)
4786 -- updating old entry
4787 Just _ -> return vars
4789 let mp2 = Map.insert key acc mp1
4790 return $ SessionState
4791 { sessionCurTime = curTime
4792 , sessionEventTime = curTime
4793 , sessionCount = cnt1
4794 , sessionTimerHeap = hp1
4795 , sessionKeyValueMap = mp2
4796 , sessionOutputStream = out1
4799 -- Got a timer tick event
4800 sstep sessionState@SessionState{..} Nothing =
4801 let curTime = addToAbsTime sessionCurTime tickMs
4802 in ejectExpired sessionState curTime
4804 flush session@SessionState{..} = do
4805 (hp', mp', out, count) <-
4808 , sessionKeyValueMap
4813 { sessionCount = count
4814 , sessionTimerHeap = hp'
4815 , sessionKeyValueMap = mp'
4816 , sessionOutputStream = out
4824 -- delete from map and output the fold accumulator
4825 ejectEntry hp mp out cnt acc key = do
4827 let out1 = (key, fromEither sess) `K.cons` out
4828 let mp1 = Map.delete key mp
4829 return (hp, mp1, out1, cnt - 1)
4831 ejectAll (hp, mp, out, !cnt) = do
4832 let hres = H.uncons hp
4834 Just (Entry _ key, hp1) -> do
4835 r <- case Map.lookup key mp of
4836 Nothing -> return (hp1, mp, out, cnt)
4837 Just (Tuple' _ acc) -> ejectEntry hp1 mp out cnt acc key
4840 assert (Map.null mp) (return ())
4841 return (hp, mp, out, cnt)
4843 ejectOne (hp, mp, out, !cnt) = do
4844 let hres = H.uncons hp
4846 Just (Entry expiry key, hp1) ->
4847 case Map.lookup key mp of
4848 Nothing -> ejectOne (hp1, mp, out, cnt)
4849 Just (Tuple' latestTS acc) -> do
4850 let expiry1 = addToAbsTime latestTS timeoutMs
4851 if not reset || expiry1 <= expiry
4852 then ejectEntry hp1 mp out cnt acc key
4854 -- reset the session timeout and continue
4855 let hp2 = H.insert (Entry expiry1 key) hp1
4856 in ejectOne (hp2, mp, out, cnt)
4858 assert (Map.null mp) (return ())
4859 return (hp, mp, out, cnt)
4861 ejectExpired session@SessionState{..} curTime = do
4862 (hp', mp', out, count) <-
4863 ejectLoop sessionTimerHeap sessionKeyValueMap K.nil sessionCount
4865 { sessionCurTime = curTime
4866 , sessionCount = count
4867 , sessionTimerHeap = hp'
4868 , sessionKeyValueMap = mp'
4869 , sessionOutputStream = out
4874 ejectLoop hp mp out !cnt = do
4875 let hres = H.uncons hp
4877 Just (Entry expiry key, hp1) -> do
4879 if curTime >= expiry
4880 then return (True, False)
4886 case Map.lookup key mp of
4887 Nothing -> ejectLoop hp1 mp out cnt
4888 Just (Tuple' latestTS acc) -> do
4889 let expiry1 = addToAbsTime latestTS timeoutMs
4890 if expiry1 <= curTime || not reset || force
4892 (hp2,mp1,out1,cnt1) <-
4893 ejectEntry hp1 mp out cnt acc key
4894 ejectLoop hp2 mp1 out1 cnt1
4896 -- reset the session timeout and continue
4897 let hp2 = H.insert (Entry expiry1 key) hp1
4898 in ejectLoop hp2 mp out cnt
4899 else return (hp, mp, out, cnt)
4901 assert (Map.null mp) (return ())
4902 return (hp, mp, out, cnt)
4904 -- merge timer events in the stream
4905 stream = Serial.map Just str `Par.parallelFst` repeatM timer
4907 liftIO $ threadDelay (round $ tick * 1000000)
4910-- | Like 'classifySessionsOf' but the session is kept alive if an event is
4911-- received within the session window. The session times out and gets closed
4912-- only if no event is received within the specified session window size.
4914-- If the ejection predicate returns 'True', the session that was idle for
4915-- the longest time is ejected before inserting a new session.
4918-- classifyKeepAliveSessions timeout pred = classifySessionsBy 1 timeout True pred
4923{-# INLINABLE classifyKeepAliveSessions #-}
4924classifyKeepAliveSessions
4925 :: (IsStream t, MonadAsync m, Ord k)
4926 => Double -- ^ session inactive timeout
4927 -> (Int -> m Bool) -- ^ predicate to eject sessions on session count
4928 -> Fold m a (Either b b) -- ^ Fold to be applied to session payload data
4929 -> t m (k, a, AbsTime) -- ^ session key, data, timestamp
4931classifyKeepAliveSessions tmout =
4932 classifySessionsBy 1 tmout True
4934------------------------------------------------------------------------------
4935-- Keyed tumbling windows
4936------------------------------------------------------------------------------
4938-- Tumbling windows is a special case of sliding windows where the window slide
4939-- is the same as the window size. Or it can be a special case of session
4940-- windows where the reset flag is set to False.
4942-- XXX instead of using the early termination flag in the stream, we can use an
4943-- early terminating fold instead.
4946-- | Split the stream into fixed size chunks of specified size. Within each
4947-- such chunk fold the elements in buckets identified by the keys. A particular
4948-- bucket fold can be terminated early if a closing flag is encountered in an
4949-- element for that key.
4952{-# INLINABLE classifyChunksOf #-}
4954 :: (IsStream t, MonadAsync m, Ord k)
4955 => Int -- ^ window size
4956 -> Fold m a b -- ^ Fold to be applied to window events
4957 -> t m (k, a, Bool) -- ^ window key, data, close event
4959classifyChunksOf wsize = classifyChunksBy wsize False
4962-- | Split the stream into fixed size time windows of specified interval in
4963-- seconds. Within each such window, fold the elements in sessions identified
4964-- by the session keys. The fold result is emitted in the output stream if the
4965-- fold returns a 'Left' result or if the time window ends.
4967-- Session @timestamp@ in the input stream is an absolute time from some epoch,
4968-- characterizing the time when the input element was generated. To detect
4969-- session window end, a monotonic event time clock is maintained synced with
4970-- the timestamps with a clock resolution of 1 second.
4972-- If the ejection predicate returns 'True', the session with the longest
4973-- lifetime is ejected before inserting a new session.
4976-- classifySessionsOf interval pred = classifySessionsBy 1 interval False pred
4981-- $ S.classifySessionsOf 3 (const (return False)) (fmap Right FL.toList)
4982-- $ S.map (\(ts,(k,a)) -> (k, a, ts))
4985-- $ (,) <$> S.fromList [1,2,3] <*> S.fromList [1,2,3]
4990{-# INLINABLE classifySessionsOf #-}
4992 :: (IsStream t, MonadAsync m, Ord k)
4993 => Double -- ^ time window size
4994 -> (Int -> m Bool) -- ^ predicate to eject sessions on session count
4995 -> Fold m a (Either b b) -- ^ Fold to be applied to session events
4996 -> t m (k, a, AbsTime) -- ^ session key, data, timestamp
4998classifySessionsOf interval =
4999 classifySessionsBy 1 interval False
5001------------------------------------------------------------------------------
5003------------------------------------------------------------------------------
5005-- | Run a side effect before the stream yields its first element.
5007-- > before action xs = 'nilM' action <> xs
5010{-# INLINE before #-}
5011before :: (IsStream t, Monad m) => m b -> t m a -> t m a
5012before action xs = D.fromStreamD $ D.before action $ D.toStreamD xs
5014-- | Run a side effect at the end of the stream. The side effect won't run if
5015-- the stream is garbage collected before it reached the end.
5017-- > after_ action xs = xs <> 'nilM' action
5019-- This has slightly better performance than 'after'.
5023{-# INLINE after_ #-}
5024after_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
5025after_ action xs = D.fromStreamD $ D.after_ action $ D.toStreamD xs
5027-- | Run a side effect at the end of the stream or if it is garbage collected
5028-- even before reaching the end.
5033after :: (IsStream t, MonadIO m, MonadBaseControl IO m)
5034 => m b -> t m a -> t m a
5035after action xs = D.fromStreamD $ D.after action $ D.toStreamD xs
5037-- | Run a side effect whenever the stream aborts due to an exception.
5040{-# INLINE onException #-}
5041onException :: (IsStream t, MonadCatch m) => m b -> t m a -> t m a
5042onException action xs = D.fromStreamD $ D.onException action $ D.toStreamD xs
5044-- | Run a side effect at the end of the stream or if it aborts due to an
5045-- exception before it could reach the end. The side effect is not run if the
5046-- stream is garbage collected before reaching the end.
5048-- This has slightly better performance than 'finally'.
5052{-# INLINE finally_ #-}
5053finally_ :: (IsStream t, MonadCatch m) => m b -> t m a -> t m a
5054finally_ action xs = D.fromStreamD $ D.finally_ action $ D.toStreamD xs
5056-- | Run a side effect at the end of the stream, or if it aborts due to an
5057-- exception or if it is garbage collected before it could reach the end.
5061{-# INLINE finally #-}
5062finally :: (IsStream t, MonadAsync m, MonadCatch m) => m b -> t m a -> t m a
5063finally action xs = D.fromStreamD $ D.finally action $ D.toStreamD xs
5065-- | Run the first action before the stream starts and remember its output,
5066-- generate a stream using the output, run the second action using the
5067-- remembered value as an argument whenever the stream ends normally or due to
5068-- an exception. The second action won't run if the stream is garbage collected
5069-- before it could reach the end.
5071-- This has slightly better performance than 'bracket'.
5075{-# INLINE bracket_ #-}
5076bracket_ :: (IsStream t, MonadCatch m)
5077 => m b -> (b -> m c) -> (b -> t m a) -> t m a
5078bracket_ bef aft bet = D.fromStreamD $
5079 D.bracket_ bef aft (toStreamD . bet)
5081-- | Run the first action before the stream starts and remember its output,
5082-- generate a stream using the output, run the second action using the
5083-- remembered value as an argument whenever the stream ends normally, due to
5084-- an exception or if it is garbage collected after a partial lazy evaluation.
5088{-# INLINE bracket #-}
5089bracket :: (IsStream t, MonadAsync m, MonadCatch m)
5090 => m b -> (b -> m c) -> (b -> t m a) -> t m a
5091bracket bef aft bet = D.fromStreamD $
5092 D.bracket bef aft (toStreamD . bet)
5094-- | When evaluating a stream if an exception occurs, stream evaluation aborts
5095-- and the specified exception handler is run with the exception as argument.
5098{-# INLINE handle #-}
5099handle :: (IsStream t, MonadCatch m, Exception e)
5100 => (e -> t m a) -> t m a -> t m a
5102 D.fromStreamD $ D.handle (D.toStreamD . handler) $ D.toStreamD xs
5104-- Keep concating either streams as long as rights are generated, stop as soon
5105-- as a left is generated and concat the left stream.
5107-- See also: 'handle'
5113 :: -- (IsStream t, MonadAsync m) =>
5114 (forall x. t m x -> t m x -> t m x)
5115 -> (a -> t m (Either (t m b) b))
5118concatMapEitherWith = undefined
5121------------------------------------------------------------------------------
5122-- Generalize the underlying monad
5123------------------------------------------------------------------------------
5125-- | Transform the inner monad of a stream using a natural transformation.
5130hoist :: (Monad m, Monad n)
5131 => (forall x. m x -> n x) -> SerialT m a -> SerialT n a
5132hoist f xs = fromStreamS $ S.hoist f (toStreamS xs)
5134-- | Generalize the inner monad of the stream from 'Identity' to any monad.
5138{-# INLINE generally #-}
5139generally :: (IsStream t, Monad m) => t Identity a -> t m a
5140generally xs = fromStreamS $ S.hoist (return . runIdentity) (toStreamS xs)
5142------------------------------------------------------------------------------
5143-- Add and remove a monad transformer
5144------------------------------------------------------------------------------
5146-- | Lift the inner monad @m@ of a stream @t m a@ to @tr m@ using the monad
5151{-# INLINE liftInner #-}
5152liftInner :: (Monad m, IsStream t, MonadTrans tr, Monad (tr m))
5153 => t m a -> t (tr m) a
5154liftInner xs = fromStreamD $ D.liftInner (toStreamD xs)
5156------------------------------------------------------------------------------
5157-- Sharing read only state in a stream
5158------------------------------------------------------------------------------
5160-- | Evaluate the inner monad of a stream as 'ReaderT'.
5164{-# INLINE runReaderT #-}
5165runReaderT :: (IsStream t, Monad m) => m s -> t (ReaderT s m) a -> t m a
5166runReaderT s xs = fromStreamD $ D.runReaderT s (toStreamD xs)
5168-- | Run a stream transformation using a given environment.
5170-- See also: 'Serial.map'
5174{-# INLINE usingReaderT #-}
5176 :: (Monad m, IsStream t)
5178 -> (t (ReaderT r m) a -> t (ReaderT r m) a)
5181usingReaderT r f xs = runReaderT r $ f $ liftInner xs
5183------------------------------------------------------------------------------
5184-- Sharing read write state in a stream
5185------------------------------------------------------------------------------
5187-- | Evaluate the inner monad of a stream as 'StateT'.
5189-- This is supported only for 'SerialT' as concurrent state updation may not be
5194{-# INLINE evalStateT #-}
5195evalStateT :: Monad m => m s -> SerialT (StateT s m) a -> SerialT m a
5196evalStateT s xs = fromStreamD $ D.evalStateT s (toStreamD xs)
5198-- | Run a stateful (StateT) stream transformation using a given state.
5200-- This is supported only for 'SerialT' as concurrent state updation may not be
5203-- See also: 'scanl''
5207{-# INLINE usingStateT #-}
5211 -> (SerialT (StateT s m) a -> SerialT (StateT s m) a)
5214usingStateT s f xs = evalStateT s $ f $ liftInner xs
5216-- | Evaluate the inner monad of a stream as 'StateT' and emit the resulting
5217-- state and value pair after each step.
5219-- This is supported only for 'SerialT' as concurrent state updation may not be
5224{-# INLINE runStateT #-}
5225runStateT :: Monad m => m s -> SerialT (StateT s m) a -> SerialT m (s, a)
5226runStateT 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