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 postscanlM' with monadic initial we can use this code
2602 -- let r = postscanlM'
2603 -- (\(s, _) a -> step s a)
2604 -- (fmap (,undefined) initial)
2608 postscanlM' (\(s, _) a -> step s a) (s0, undefined) stream
2613------------------------------------------------------------------------------
2615------------------------------------------------------------------------------
2617-- | Map a 'Maybe' returning function to a stream, filter out the 'Nothing'
2618-- elements, and return a stream of values extracted from 'Just'.
2623-- mapMaybe f = S.map 'fromJust' . S.filter 'isJust' . S.map f
2627{-# INLINE mapMaybe #-}
2628mapMaybe :: (IsStream t, Monad m) => (a -> Maybe b) -> t m a -> t m b
2629mapMaybe f m = fromStreamS $ S.mapMaybe f $ toStreamS m
2631-- | Like 'mapMaybe' but maps a monadic function.
2636-- mapMaybeM f = S.map 'fromJust' . S.filter 'isJust' . S.mapM f
2639-- /Concurrent (do not use with 'parallely' on infinite streams)/
2642{-# INLINE_EARLY mapMaybeM #-}
2643mapMaybeM :: (IsStream t, MonadAsync m, Functor (t m))
2644 => (a -> m (Maybe b)) -> t m a -> t m b
2645mapMaybeM f = fmap fromJust . filter isJust . K.mapM f
2647{-# RULES "mapMaybeM serial" mapMaybeM = mapMaybeMSerial #-}
2648{-# INLINE mapMaybeMSerial #-}
2649mapMaybeMSerial :: Monad m => (a -> m (Maybe b)) -> SerialT m a -> SerialT m b
2650mapMaybeMSerial f m = fromStreamD $ D.mapMaybeM f $ toStreamD m
2652-- | In a stream of 'Maybe's, discard 'Nothing's and unwrap 'Just's.
2656catMaybes :: (IsStream t, Monad m, Functor (t m)) => t m (Maybe a) -> t m a
2657catMaybes = fmap fromJust . filter isJust
2659------------------------------------------------------------------------------
2660-- Transformation by Reordering
2661------------------------------------------------------------------------------
2663-- XXX Use a compact region list to temporarily store the list, in both reverse
2664-- as well as in reverse'.
2666-- /Note:/ 'reverse'' is much faster than this, use that when performance
2669-- > reverse = S.foldlT (flip S.cons) S.nil
2671-- | Returns the elements of the stream in reverse order. The stream must be
2672-- finite. Note that this necessarily buffers the entire stream in memory.
2674-- /Since 0.7.0 (Monad m constraint)/
2677{-# INLINE reverse #-}
2678reverse :: (IsStream t, Monad m) => t m a -> t m a
2679reverse s = fromStreamS $ S.reverse $ toStreamS s
2681-- | Like 'reverse' but several times faster, requires a 'Storable' instance.
2684{-# INLINE reverse' #-}
2685reverse' :: (IsStream t, MonadIO m, Storable a) => t m a -> t m a
2686reverse' s = fromStreamD $ D.reverse' $ toStreamD s
2688------------------------------------------------------------------------------
2689-- Transformation by Inserting
2690------------------------------------------------------------------------------
2692-- intersperseM = intersperseBySpan 1
2694-- | Insert an effect and its output before consuming an element of a stream
2695-- except the first one.
2698-- >>> S.toList $ S.trace putChar $ S.intersperseM (putChar '.' >> return ',') $ S.fromList "hello"
2699-- > h.,e.,l.,l.,o"h,e,l,l,o"
2703{-# INLINE intersperseM #-}
2704intersperseM :: (IsStream t, MonadAsync m) => m a -> t m a -> t m a
2705intersperseM m = fromStreamS . S.intersperseM m . toStreamS
2707-- | Insert a side effect before consuming an element of a stream except the
2711-- >>> S.drain $ S.trace putChar $ S.intersperseM_ (putChar '.') $ S.fromList "hello"
2716{-# INLINE intersperseM_ #-}
2717intersperseM_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
2718intersperseM_ m = fromStreamD . D.intersperseM_ m . toStreamD
2720-- | Insert a pure value between successive elements of a stream.
2723-- > S.toList $ S.intersperse ',' $ S.fromList "hello"
2728{-# INLINE intersperse #-}
2729intersperse :: (IsStream t, MonadAsync m) => a -> t m a -> t m a
2730intersperse a = fromStreamS . S.intersperse a . toStreamS
2732-- | Insert an effect and its output after consuming an element of a stream.
2735-- >>> S.toList $ S.trace putChar $ S.intersperseSuffix (putChar '.' >> return ',') $ S.fromList "hello"
2736-- > h.,e.,l.,l.,o.,"h,e,l,l,o,"
2740{-# INLINE intersperseSuffix #-}
2741intersperseSuffix :: (IsStream t, MonadAsync m) => m a -> t m a -> t m a
2742intersperseSuffix m = fromStreamD . D.intersperseSuffix m . toStreamD
2744-- | Insert a side effect after consuming an element of a stream.
2747-- > S.mapM_ putChar $ S.intersperseSuffix_ (threadDelay 1000000) $ S.fromList "hello"
2752{-# INLINE intersperseSuffix_ #-}
2753intersperseSuffix_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
2754intersperseSuffix_ m = fromStreamD . D.intersperseSuffix_ m . toStreamD
2756-- | Insert a side effect before consuming an element of a stream.
2759-- >>> S.toList $ S.trace putChar $ S.interspersePrefix_ (putChar '.' >> return ',') $ S.fromList "hello"
2760-- > .h.e.l.l.o"hello"
2763-- See also: 'trace_'
2769{-# INLINE interspersePrefix_ #-}
2770interspersePrefix_ :: (IsStream t, MonadAsync m) => m b -> t m a -> t m a
2771interspersePrefix_ m = mapM (\x -> void m >> return x)
2773-- Note: delay must be serial.
2775-- | Introduce a delay of specified seconds before consuming an element of the
2776-- stream except the first one.
2779-- >>> S.mapM_ print $ S.timestamped $ S.delay 1 $ S.enumerateFromTo 1 3
2780-- > (AbsTime (TimeSpec {sec = 2502706, nsec = 751137000}),1)
2781-- > (AbsTime (TimeSpec {sec = 2502707, nsec = 743535000}),2)
2782-- > (AbsTime (TimeSpec {sec = 2502708, nsec = 749758000}),3)
2788delay :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
2789delay n = intersperseM_ $ liftIO $ threadDelay $ round $ n * 1000000
2791-- Note: delay must be serial.
2793-- | Introduce a delay of specified seconds after consuming an element of a
2797-- >>> S.mapM_ print $ S.timestamped $ S.delayPost 1 $ S.enumerateFromTo 1 3
2798-- > (AbsTime (TimeSpec {sec = 2502826, nsec = 119030000}),1)
2799-- > (AbsTime (TimeSpec {sec = 2502827, nsec = 111393000}),2)
2800-- > (AbsTime (TimeSpec {sec = 2502828, nsec = 112221000}),3)
2805{-# INLINE delayPost #-}
2806delayPost :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
2807delayPost n = intersperseSuffix_ $ liftIO $ threadDelay $ round $ n * 1000000
2809-- Note: delay must be serial, that's why 'trace_' is used.
2811-- | Introduce a delay of specified seconds before consuming an element of a
2815-- >>> S.mapM_ print $ S.timestamped $ S.delayPre 1 $ S.enumerateFromTo 1 3
2816-- > (AbsTime (TimeSpec {sec = 2502207, nsec = 533177000}),1)
2817-- > (AbsTime (TimeSpec {sec = 2502208, nsec = 530859000}),2)
2818-- > (AbsTime (TimeSpec {sec = 2502209, nsec = 531619000}),3)
2823{-# INLINE delayPre #-}
2824delayPre :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
2825delayPre n = trace_ $ liftIO $ threadDelay $ round $ n * 1000000
2827-- | Like 'intersperseSuffix' but intersperses an effectful action into the
2828-- input stream after every @n@ elements and after the last element.
2831-- > S.toList $ S.intersperseSuffixBySpan 2 (return ',') $ S.fromList "hello"
2837{-# INLINE intersperseSuffixBySpan #-}
2838intersperseSuffixBySpan :: (IsStream t, MonadAsync m)
2839 => Int -> m a -> t m a -> t m a
2840intersperseSuffixBySpan n eff =
2841 fromStreamD . D.intersperseSuffixBySpan n eff . toStreamD
2844-- | Intersperse a monadic action into the input stream after every @n@
2848-- > S.toList $ S.intersperseBySpan 2 (return ',') $ S.fromList "hello"
2853{-# INLINE intersperseBySpan #-}
2854intersperseBySpan :: IsStream t => Int -> m a -> t m a -> t m a
2855intersperseBySpan _n _f _xs = undefined
2858-- | Intersperse a monadic action into the input stream after every @n@
2862-- > S.drain $ S.interjectSuffix 1 (putChar ',') $ S.mapM (\\x -> threadDelay 1000000 >> putChar x) $ S.fromList "hello"
2867{-# INLINE interjectSuffix #-}
2869 :: (IsStream t, MonadAsync m)
2870 => Double -> m a -> t m a -> t m a
2871interjectSuffix n f xs = xs `Par.parallelFst` repeatM timed
2872 where timed = liftIO (threadDelay (round $ n * 1000000)) >> f
2874-- | @insertBy cmp elem stream@ inserts @elem@ before the first element in
2875-- @stream@ that is less than @elem@ when compared using @cmp@.
2878-- insertBy cmp x = 'mergeBy' cmp ('yield' x)
2882-- > S.toList $ S.insertBy compare 2 $ S.fromList [1,3,5]
2887{-# INLINE insertBy #-}
2889 (IsStream t, Monad m) => (a -> a -> Ordering) -> a -> t m a -> t m a
2890insertBy cmp x m = fromStreamS $ S.insertBy cmp x (toStreamS m)
2892------------------------------------------------------------------------------
2894------------------------------------------------------------------------------
2896-- | Deletes the first occurrence of the element in the stream that satisfies
2897-- the given equality predicate.
2900-- > S.toList $ S.deleteBy (==) 3 $ S.fromList [1,3,3,5]
2905{-# INLINE deleteBy #-}
2906deleteBy :: (IsStream t, Monad m) => (a -> a -> Bool) -> a -> t m a -> t m a
2907deleteBy cmp x m = fromStreamS $ S.deleteBy cmp x (toStreamS m)
2909------------------------------------------------------------------------------
2911------------------------------------------------------------------------------
2914-- > indexed = S.postscanl' (\(i, _) x -> (i + 1, x)) (-1,undefined)
2915-- > indexed = S.zipWith (,) (S.enumerateFrom 0)
2917-- Pair each element in a stream with its index, starting from index 0.
2920-- > S.toList $ S.indexed $ S.fromList "hello"
2921-- [(0,'h'),(1,'e'),(2,'l'),(3,'l'),(4,'o')]
2925{-# INLINE indexed #-}
2926indexed :: (IsStream t, Monad m) => t m a -> t m (Int, a)
2927indexed = fromStreamD . D.indexed . toStreamD
2930-- > indexedR n = S.postscanl' (\(i, _) x -> (i - 1, x)) (n + 1,undefined)
2931-- > indexedR n = S.zipWith (,) (S.enumerateFromThen n (n - 1))
2933-- Pair each element in a stream with its index, starting from the
2934-- given index @n@ and counting down.
2937-- > S.toList $ S.indexedR 10 $ S.fromList "hello"
2938-- [(10,'h'),(9,'e'),(8,'l'),(7,'l'),(6,'o')]
2942{-# INLINE indexedR #-}
2943indexedR :: (IsStream t, Monad m) => Int -> t m a -> t m (Int, a)
2944indexedR n = fromStreamD . D.indexedR n . toStreamD
2946-- Note: The timestamp stream must be the second stream in the zip so that the
2947-- timestamp is generated after generating the stream element and not before.
2948-- If we do not do that then the following example will generate the same
2949-- timestamp for first two elements:
2951-- S.mapM_ print $ S.timestamped $ S.delay $ S.enumerateFromTo 1 3
2953-- | Pair each element in a stream with an absolute timestamp, using a clock of
2954-- specified granularity. The timestamp is generated just before the element
2958-- >>> S.mapM_ print $ S.timestampWith 0.01 $ S.delay 1 $ S.enumerateFromTo 1 3
2963{-# INLINE timestampWith #-}
2964timestampWith :: (IsStream t, MonadAsync m, Functor (t m))
2965 => Double -> t m a -> t m (AbsTime, a)
2966timestampWith g stream = Z.zipWith (flip (,)) stream (absTimesWith g)
2968-- TBD: check performance vs a custom implementation without using zipWith.
2970-- | Pair each element in a stream with an absolute timestamp, using a clock of
2971-- 10 ms granularity. The timestamp is generated just before the element is
2975-- >>> S.mapM_ print $ S.timestamped $ S.delay 1 $ S.enumerateFromTo 1 3
2976-- (AbsTime (TimeSpec {sec = 2460689, nsec = 641121000}),1)
2977-- (AbsTime (TimeSpec {sec = 2460690, nsec = 639334000}),2)
2978-- (AbsTime (TimeSpec {sec = 2460691, nsec = 644479000}),3)
2983{-# INLINE timestamped #-}
2984timestamped :: (IsStream t, MonadAsync m, Functor (t m))
2985 => t m a -> t m (AbsTime, a)
2986timestamped = timestampWith 0.01
2988-- | Pair each element in a stream with relative times starting from 0, using a
2989-- clock with the specified granularity. The time is measured just before the
2990-- element is consumed.
2993-- >>> S.mapM_ print $ S.timeIndexWith 0.01 $ S.delay 1 $ S.enumerateFromTo 1 3
2998{-# INLINE timeIndexWith #-}
2999timeIndexWith :: (IsStream t, MonadAsync m, Functor (t m))
3000 => Double -> t m a -> t m (RelTime64, a)
3001timeIndexWith g stream = Z.zipWith (flip (,)) stream (relTimesWith g)
3003-- | Pair each element in a stream with relative times starting from 0, using a
3004-- 10 ms granularity clock. The time is measured just before the element is
3008-- >>> S.mapM_ print $ S.timeIndexed $ S.delay 1 $ S.enumerateFromTo 1 3
3009-- (RelTime64 (NanoSecond64 0),1)
3010-- (RelTime64 (NanoSecond64 996239000),2)
3011-- (RelTime64 (NanoSecond64 1996712000),3)
3016{-# INLINE timeIndexed #-}
3017timeIndexed :: (IsStream t, MonadAsync m, Functor (t m))
3018 => t m a -> t m (RelTime64, a)
3019timeIndexed = timeIndexWith 0.01
3021------------------------------------------------------------------------------
3023------------------------------------------------------------------------------
3025-- | Compare two streams for equality using an equality function.
3028{-# INLINABLE eqBy #-}
3029eqBy :: (IsStream t, Monad m) => (a -> b -> Bool) -> t m a -> t m b -> m Bool
3032-- | Compare two streams lexicographically using a comparison function.
3035{-# INLINABLE cmpBy #-}
3037 :: (IsStream t, Monad m)
3038 => (a -> b -> Ordering) -> t m a -> t m b -> m Ordering
3041------------------------------------------------------------------------------
3043------------------------------------------------------------------------------
3045-- | Merge two streams using a comparison function. The head elements of both
3046-- the streams are compared and the smaller of the two elements is emitted, if
3047-- both elements are equal then the element from the first stream is used
3050-- If the streams are sorted in ascending order, the resulting stream would
3051-- also remain sorted in ascending order.
3054-- > S.toList $ S.mergeBy compare (S.fromList [1,3,5]) (S.fromList [2,4,6,8])
3059{-# INLINABLE mergeBy #-}
3061 (IsStream t, Monad m) => (a -> a -> Ordering) -> t m a -> t m a -> t m a
3062mergeBy f m1 m2 = fromStreamS $ S.mergeBy f (toStreamS m1) (toStreamS m2)
3064-- | Like 'mergeBy' but with a monadic comparison function.
3066-- Merge two streams randomly:
3069-- > randomly _ _ = randomIO >>= \x -> return $ if x then LT else GT
3070-- > S.toList $ S.mergeByM randomly (S.fromList [1,1,1,1]) (S.fromList [2,2,2,2])
3074-- Merge two streams in a proportion of 2:1:
3077-- proportionately m n = do
3078-- ref <- newIORef $ cycle $ concat [replicate m LT, replicate n GT]
3079-- return $ \\_ _ -> do
3080-- r <- readIORef ref
3081-- writeIORef ref $ tail r
3085-- f <- proportionately 2 1
3086-- xs <- S.toList $ S.mergeByM f (S.fromList [1,1,1,1,1,1]) (S.fromList [2,2,2])
3090-- [1,1,2,1,1,2,1,1,2]
3094{-# INLINABLE mergeByM #-}
3096 :: (IsStream t, Monad m)
3097 => (a -> a -> m Ordering) -> t m a -> t m a -> t m a
3098mergeByM f m1 m2 = fromStreamS $ S.mergeByM f (toStreamS m1) (toStreamS m2)
3101-- | Like 'mergeByM' but stops merging as soon as any of the two streams stops.
3102{-# INLINABLE mergeEndByAny #-}
3104 :: (IsStream t, Monad m)
3105 => (a -> a -> m Ordering) -> t m a -> t m a -> t m a
3106mergeEndByAny f m1 m2 = fromStreamD $
3107 D.mergeEndByAny f (toStreamD m1) (toStreamD m2)
3109-- Like 'mergeByM' but stops merging as soon as the first stream stops.
3110{-# INLINABLE mergeEndByFirst #-}
3112 :: (IsStream t, Monad m)
3113 => (a -> a -> m Ordering) -> t m a -> t m a -> t m a
3114mergeEndByFirst f m1 m2 = fromStreamS $
3115 D.mergeEndByFirst f (toStreamD m1) (toStreamD m2)
3118-- Holding this back for now, we may want to use the name "merge" differently
3120-- | Same as @'mergeBy' 'compare'@.
3123-- > S.toList $ S.merge (S.fromList [1,3,5]) (S.fromList [2,4,6,8])
3128{-# INLINABLE merge #-}
3130 (IsStream t, Monad m, Ord a) => t m a -> t m a -> t m a
3131merge = mergeBy compare
3134-- | Like 'mergeBy' but merges concurrently (i.e. both the elements being
3135-- merged are generated concurrently).
3138{-# INLINE mergeAsyncBy #-}
3139mergeAsyncBy :: (IsStream t, MonadAsync m)
3140 => (a -> a -> Ordering) -> t m a -> t m a -> t m a
3141mergeAsyncBy f = mergeAsyncByM (\a b -> return $ f a b)
3143-- | Like 'mergeByM' but merges concurrently (i.e. both the elements being
3144-- merged are generated concurrently).
3147{-# INLINE mergeAsyncByM #-}
3148mergeAsyncByM :: (IsStream t, MonadAsync m)
3149 => (a -> a -> m Ordering) -> t m a -> t m a -> t m a
3150mergeAsyncByM f m1 m2 = fromStreamD $
3151 D.mergeByM f (D.mkParallelD $ toStreamD m1) (D.mkParallelD $ toStreamD m2)
3153------------------------------------------------------------------------------
3155------------------------------------------------------------------------------
3157-- | @concatMapWith merge map stream@ is a two dimensional looping combinator.
3158-- The first argument specifies a merge or concat function that is used to
3159-- merge the streams generated by applying the second argument i.e. the @map@
3160-- function to each element of the input stream. The concat function could be
3161-- 'serial', 'parallel', 'async', 'ahead' or any other zip or merge function
3162-- and the second argument could be any stream generation function using a
3165-- /Compare 'foldMapWith'/
3168{-# INLINE concatMapWith #-}
3171 => (t m b -> t m b -> t m b)
3175concatMapWith = K.concatMapBy
3177-- | Like 'concatMapWith' but carries a state which can be used to share
3178-- information across multiple steps of concat.
3181-- concatSmapMWith combine f initial = concatMapWith combine id . smapM f initial
3186{-# INLINE concatSmapMWith #-}
3188 :: (IsStream t, Monad m)
3189 => (t m b -> t m b -> t m b)
3190 -> (s -> a -> m (s, t m b))
3194concatSmapMWith combine f initial = concatMapWith combine id . smapM f initial
3196-- | Map a stream producing function on each element of the stream and then
3197-- flatten the results into a single stream.
3200-- concatMap f = 'concat . map f'
3201-- concatMap = 'concatMapWith' 'Serial.serial'
3202-- concatMap f = 'concatMapM' (return . f)
3203-- concatMap f = 'concatUnfold' (UF.lmap f UF.fromStream)
3207{-# INLINE concatMap #-}
3208concatMap ::(IsStream t, Monad m) => (a -> t m b) -> t m a -> t m b
3209concatMap f m = fromStreamD $ D.concatMap (toStreamD . f) (toStreamD m)
3211-- | Flatten a stream of streams to a single stream.
3214-- concat = concatMap id
3218{-# INLINE concat #-}
3219concat :: (IsStream t, Monad m) => t m (t m a) -> t m a
3220concat = concatMap id
3222-- | Append the outputs of two streams, yielding all the elements from the
3223-- first stream and then yielding all the elements from the second stream.
3225-- IMPORTANT NOTE: This could be 100x faster than @serial/<>@ for appending a
3226-- few (say 100) streams because it can fuse via stream fusion. However, it
3227-- does not scale for a large number of streams (say 1000s) and becomes
3228-- qudartically slow. Therefore use this for custom appending of a few streams
3229-- but use 'concatMap' or 'concatMapWith serial' for appending @n@ streams or
3230-- infinite containers of streams.
3233{-# INLINE append #-}
3234append ::(IsStream t, Monad m) => t m b -> t m b -> t m b
3235append m1 m2 = fromStreamD $ D.append (toStreamD m1) (toStreamD m2)
3237-- XXX Same as 'wSerial'. We should perhaps rename wSerial to interleave.
3238-- XXX Document the interleaving behavior of side effects in all the
3239-- interleaving combinators.
3240-- XXX Write time-domain equivalents of these. In the time domain we can
3241-- interleave two streams such that the value of second stream is always taken
3242-- from its last value even if no new value is being yielded, like
3243-- zipWithLatest. It would be something like interleaveWithLatest.
3245-- | Interleaves the outputs of two streams, yielding elements from each stream
3246-- alternately, starting from the first stream. If any of the streams finishes
3247-- early the other stream continues alone until it too finishes.
3249-- >>> :set -XOverloadedStrings
3250-- >>> interleave "ab" ",,,," :: SerialT Identity Char
3252-- >>> interleave "abcd" ",," :: SerialT Identity Char
3255-- 'interleave' is dual to 'interleaveMin', it can be called @interleaveMax@.
3257-- Do not use at scale in concatMapWith.
3260{-# INLINE interleave #-}
3261interleave ::(IsStream t, Monad m) => t m b -> t m b -> t m b
3262interleave m1 m2 = fromStreamD $ D.interleave (toStreamD m1) (toStreamD m2)
3264-- | Interleaves the outputs of two streams, yielding elements from each stream
3265-- alternately, starting from the first stream. As soon as the first stream
3266-- finishes, the output stops, discarding the remaining part of the second
3267-- stream. In this case, the last element in the resulting stream would be from
3268-- the second stream. If the second stream finishes early then the first stream
3269-- still continues to yield elements until it finishes.
3271-- >>> :set -XOverloadedStrings
3272-- >>> interleaveSuffix "abc" ",,,," :: SerialT Identity Char
3274-- >>> interleaveSuffix "abc" "," :: SerialT Identity Char
3277-- 'interleaveSuffix' is a dual of 'interleaveInfix'.
3279-- Do not use at scale in concatMapWith.
3282{-# INLINE interleaveSuffix #-}
3283interleaveSuffix ::(IsStream t, Monad m) => t m b -> t m b -> t m b
3284interleaveSuffix m1 m2 =
3285 fromStreamD $ D.interleaveSuffix (toStreamD m1) (toStreamD m2)
3287-- | Interleaves the outputs of two streams, yielding elements from each stream
3288-- alternately, starting from the first stream and ending at the first stream.
3289-- If the second stream is longer than the first, elements from the second
3290-- stream are infixed with elements from the first stream. If the first stream
3291-- is longer then it continues yielding elements even after the second stream
3294-- >>> :set -XOverloadedStrings
3295-- >>> interleaveInfix "abc" ",,,," :: SerialT Identity Char
3297-- >>> interleaveInfix "abc" "," :: SerialT Identity Char
3300-- 'interleaveInfix' is a dual of 'interleaveSuffix'.
3302-- Do not use at scale in concatMapWith.
3305{-# INLINE interleaveInfix #-}
3306interleaveInfix ::(IsStream t, Monad m) => t m b -> t m b -> t m b
3307interleaveInfix m1 m2 =
3308 fromStreamD $ D.interleaveInfix (toStreamD m1) (toStreamD m2)
3310-- | Interleaves the outputs of two streams, yielding elements from each stream
3311-- alternately, starting from the first stream. The output stops as soon as any
3312-- of the two streams finishes, discarding the remaining part of the other
3313-- stream. The last element of the resulting stream would be from the longer
3316-- >>> :set -XOverloadedStrings
3317-- >>> interleaveMin "ab" ",,,," :: SerialT Identity Char
3319-- >>> interleaveMin "abcd" ",," :: SerialT Identity Char
3322-- 'interleaveMin' is dual to 'interleave'.
3324-- Do not use at scale in concatMapWith.
3327{-# INLINE interleaveMin #-}
3328interleaveMin ::(IsStream t, Monad m) => t m b -> t m b -> t m b
3329interleaveMin m1 m2 = fromStreamD $ D.interleaveMin (toStreamD m1) (toStreamD m2)
3331-- | Schedule the execution of two streams in a fair round-robin manner,
3332-- executing each stream once, alternately. Execution of a stream may not
3333-- necessarily result in an output, a stream may chose to @Skip@ producing an
3334-- element until later giving the other stream a chance to run. Therefore, this
3335-- combinator fairly interleaves the execution of two streams rather than
3336-- fairly interleaving the output of the two streams. This can be useful in
3337-- co-operative multitasking without using explicit threads. This can be used
3338-- as an alternative to `async`.
3340-- Do not use at scale in concatMapWith.
3343{-# INLINE roundrobin #-}
3344roundrobin ::(IsStream t, Monad m) => t m b -> t m b -> t m b
3345roundrobin m1 m2 = fromStreamD $ D.roundRobin (toStreamD m1) (toStreamD m2)
3347-- | Map a stream producing monadic function on each element of the stream
3348-- and then flatten the results into a single stream. Since the stream
3349-- generation function is monadic, unlike 'concatMap', it can produce an
3350-- effect at the beginning of each iteration of the inner loop.
3353{-# INLINE concatMapM #-}
3354concatMapM :: (IsStream t, Monad m) => (a -> m (t m b)) -> t m a -> t m b
3355concatMapM f m = fromStreamD $ D.concatMapM (fmap toStreamD . f) (toStreamD m)
3357-- | Given a stream value in the underlying monad, lift and join the underlying
3358-- monad with the stream monad.
3361-- concatM = concat . yieldM
3362-- concatM = concat . lift -- requires @(MonadTrans t)@
3363-- concatM = join . lift -- requires @(MonadTrans t@, @Monad (t m))@
3366-- See also: 'concat', 'sequence'
3370{-# INLINE concatM #-}
3371concatM :: (IsStream t, Monad m) => m (t m a) -> t m a
3372concatM generator = concatMapM (\() -> generator) (yield ())
3374-- | Like 'concatMap' but uses an 'Unfold' for stream generation. Unlike
3375-- 'concatMap' this can fuse the 'Unfold' code with the inner loop and
3376-- therefore provide many times better performance.
3379{-# INLINE concatUnfold #-}
3380concatUnfold ::(IsStream t, Monad m) => Unfold m a b -> t m a -> t m b
3381concatUnfold u m = fromStreamD $ D.concatMapU u (toStreamD m)
3383-- | Like 'concatUnfold' but interleaves the streams in the same way as
3384-- 'interleave' behaves instead of appending them.
3387{-# INLINE concatUnfoldInterleave #-}
3388concatUnfoldInterleave ::(IsStream t, Monad m)
3389 => Unfold m a b -> t m a -> t m b
3390concatUnfoldInterleave u m =
3391 fromStreamD $ D.concatUnfoldInterleave u (toStreamD m)
3393-- | Like 'concatUnfold' but executes the streams in the same way as
3397{-# INLINE concatUnfoldRoundrobin #-}
3398concatUnfoldRoundrobin ::(IsStream t, Monad m)
3399 => Unfold m a b -> t m a -> t m b
3400concatUnfoldRoundrobin u m =
3401 fromStreamD $ D.concatUnfoldRoundrobin u (toStreamD m)
3403-- XXX we can swap the order of arguments to gintercalate so that the
3404-- definition of concatUnfold becomes simpler? The first stream should be
3405-- infixed inside the second one. However, if we change the order in
3406-- "interleave" as well similarly, then that will make it a bit unintuitive.
3408-- > concatUnfold unf str =
3409-- > gintercalate unf str (UF.nilM (\_ -> return ())) (repeat ())
3411-- | 'interleaveInfix' followed by unfold and concat.
3414{-# INLINE gintercalate #-}
3416 :: (IsStream t, Monad m)
3417 => Unfold m a c -> t m a -> Unfold m b c -> t m b -> t m c
3418gintercalate unf1 str1 unf2 str2 =
3419 D.fromStreamD $ D.gintercalate
3420 unf1 (D.toStreamD str1)
3421 unf2 (D.toStreamD str2)
3423-- XXX The order of arguments in "intercalate" is consistent with the list
3424-- intercalate but inconsistent with gintercalate and other stream interleaving
3425-- combinators. We can change the order of the arguments in other combinators
3426-- but then 'interleave' combinator may become a bit unintuitive because we
3427-- will be starting with the second stream.
3429-- > intercalate seed unf str = gintercalate unf str unf (repeatM seed)
3430-- > intercalate a unf str = concatUnfold unf $ intersperse a str
3432-- | 'intersperse' followed by unfold and concat.
3434-- > unwords = intercalate " " UF.fromList
3436-- >>> intercalate " " UF.fromList ["abc", "def", "ghi"]
3440{-# INLINE intercalate #-}
3441intercalate :: (IsStream t, Monad m)
3442 => b -> Unfold m b c -> t m b -> t m c
3443intercalate seed unf str = D.fromStreamD $
3444 D.concatMapU unf $ D.intersperse seed (toStreamD str)
3446-- > interpose x unf str = gintercalate unf str UF.identity (repeat x)
3448-- | Unfold the elements of a stream, intersperse the given element between the
3449-- unfolded streams and then concat them into a single stream.
3451-- > unwords = S.interpose ' '
3454{-# INLINE interpose #-}
3455interpose :: (IsStream t, Monad m)
3456 => c -> Unfold m b c -> t m b -> t m c
3457interpose x unf str =
3458 D.fromStreamD $ D.interpose (return x) unf (D.toStreamD str)
3460-- | 'interleaveSuffix' followed by unfold and concat.
3463{-# INLINE gintercalateSuffix #-}
3465 :: (IsStream t, Monad m)
3466 => Unfold m a c -> t m a -> Unfold m b c -> t m b -> t m c
3467gintercalateSuffix unf1 str1 unf2 str2 =
3468 D.fromStreamD $ D.gintercalateSuffix
3469 unf1 (D.toStreamD str1)
3470 unf2 (D.toStreamD str2)
3472-- > intercalateSuffix seed unf str = gintercalateSuffix unf str unf (repeatM seed)
3473-- > intercalateSuffix a unf str = concatUnfold unf $ intersperseSuffix a str
3475-- | 'intersperseSuffix' followed by unfold and concat.
3477-- > unlines = intercalateSuffix "\n" UF.fromList
3479-- >>> intercalate "\n" UF.fromList ["abc", "def", "ghi"]
3480-- > "abc\ndef\nghi\n"
3483{-# INLINE intercalateSuffix #-}
3484intercalateSuffix :: (IsStream t, Monad m)
3485 => b -> Unfold m b c -> t m b -> t m c
3486intercalateSuffix seed unf str = fromStreamD $ D.concatMapU unf
3487 $ D.intersperseSuffix (return seed) (D.toStreamD str)
3489-- interposeSuffix x unf str = gintercalateSuffix unf str UF.identity (repeat x)
3491-- | Unfold the elements of a stream, append the given element after each
3492-- unfolded stream and then concat them into a single stream.
3494-- > unlines = S.interposeSuffix '\n'
3497{-# INLINE interposeSuffix #-}
3498interposeSuffix :: (IsStream t, Monad m)
3499 => c -> Unfold m b c -> t m b -> t m c
3500interposeSuffix x unf str =
3501 D.fromStreamD $ D.interposeSuffix (return x) unf (D.toStreamD str)
3503------------------------------------------------------------------------------
3505------------------------------------------------------------------------------
3507-- | Like 'iterateM' but iterates after mapping a stream generator on the
3510-- Yield an input element in the output stream, map a stream generator on it
3511-- and then do the same on the resulting stream. This can be used for a depth
3512-- first traversal of a tree like structure.
3514-- Note that 'iterateM' is a special case of 'iterateMapWith':
3517-- iterateM f = iterateMapWith serial (yieldM . f) . yieldM
3520-- It can be used to traverse a tree structure. For example, to list a
3524-- Stream.iterateMapWith Stream.serial
3525-- (either Dir.toEither (const nil))
3526-- (yield (Left "tmp"))
3531{-# INLINE iterateMapWith #-}
3534 => (t m a -> t m a -> t m a)
3538iterateMapWith combine f = concatMapWith combine go
3540 go x = yield x `combine` concatMapWith combine go (f x)
3543{-# INLINE iterateUnfold #-}
3544iterateUnfold :: (IsStream t, MonadAsync m)
3545 => Unfold m a a -> t m a -> t m a
3546iterateUnfold unf xs = undefined
3549------------------------------------------------------------------------------
3551------------------------------------------------------------------------------
3553-- To traverse graphs we need a state to be carried around in the traversal.
3554-- For example, we can use a hashmap to store the visited status of nodes.
3556-- | Like 'iterateMap' but carries a state in the stream generation function.
3557-- This can be used to traverse graph like structures, we can remember the
3558-- visited nodes in the state to avoid cycles.
3560-- Note that a combination of 'iterateMap' and 'usingState' can also be used to
3561-- traverse graphs. However, this function provides a more localized state
3562-- instead of using a global state.
3568{-# INLINE iterateSmapMWith #-}
3570 :: (IsStream t, Monad m)
3571 => (t m a -> t m a -> t m a)
3572 -> (b -> a -> m (b, t m a))
3576iterateSmapMWith combine f initial stream =
3577 concatMap (\b -> concatMapWith combine (go b) stream) (yieldM initial)
3581 go b a = yield a `combine` feedback b a
3585 (\(b1, s) -> concatMapWith combine (go b1) s)
3588------------------------------------------------------------------------------
3590------------------------------------------------------------------------------
3592-- | Discard 'Right's and unwrap 'Left's in an 'Either' stream.
3596lefts :: (IsStream t, Monad m, Functor (t m)) => t m (Either a b) -> t m a
3597lefts = fmap (fromLeft undefined) . filter isLeft
3599-- | Discard 'Left's and unwrap 'Right's in an 'Either' stream.
3603rights :: (IsStream t, Monad m, Functor (t m)) => t m (Either a b) -> t m b
3604rights = fmap (fromRight undefined) . filter isRight
3606-- | In an 'Either' stream iterate on 'Left's. This is a special case of
3610-- iterateMapLeftsWith combine f = iterateMapWith combine (either f (const nil))
3613-- To traverse a directory tree:
3616-- iterateMapLeftsWith serial Dir.toEither (yield (Left "tmp"))
3621{-# INLINE iterateMapLeftsWith #-}
3624 => (t m (Either a b) -> t m (Either a b) -> t m (Either a b))
3625 -> (a -> t m (Either a b))
3628iterateMapLeftsWith combine f = iterateMapWith combine (either f (const K.nil))
3630------------------------------------------------------------------------------
3632------------------------------------------------------------------------------
3634-- Splitting operations that take a predicate and a Fold can be
3635-- expressed using parseMany. Operations like chunksOf, intervalsOf, split*,
3636-- can be expressed using parseMany when used with an appropriate Parser.
3638-- XXX We need takeGE/takeBetween to implement "some" using "many".
3640-- | Apply a 'Parser' repeatedly on a stream and emit the parsed values in the
3643-- This is the streaming equivalent of the 'Streamly.Internal.Data.Parser.many'
3646-- >>> S.toList $ S.parseMany (PR.take 2 $ PR.fromFold FL.sum) $ S.fromList [1..10]
3649-- >>> S.toList $ S.parseMany (PR.line FL.toList) $ S.fromList "hello\nworld"
3650-- > ["hello\n","world"]
3654{-# INLINE parseMany #-}
3656 :: (IsStream t, MonadThrow m)
3661 D.fromStreamD $ D.parseMany (PRK.fromParserK p) (D.toStreamD m)
3663{-# INLINE parseManyD #-}
3665 :: (IsStream t, MonadThrow m)
3670 D.fromStreamD $ D.parseMany p (D.toStreamD m)
3672-- | @parseManyTill collect test stream@ tries the parser @test@ on the input,
3673-- if @test@ fails it backtracks and tries @collect@, after @collect@ succeeds
3674-- @test@ is tried again and so on. The parser stops when @test@ succeeds. The
3675-- output of @test@ is discarded and the output of @collect@ is emitted in the
3676-- output stream. The parser fails if @collect@ fails.
3680{-# INLINE parseManyTill #-}
3682 -- (IsStream t, MonadThrow m) =>
3687parseManyTill = undefined
3689-- | Iterate a parser generating function on a stream. The initial value @b@ is
3690-- used to generate the first parser, the parser is applied on the stream and
3691-- the result is used to generate the next parser and so on.
3693-- >>> S.toList $ S.map getSum $ S.parseIterate (\b -> PR.take 2 (FL.mconcatTo b)) 0 $ S.map Sum $ S.fromList [1..10]
3694-- > [3,10,21,36,55,55]
3696-- This is the streaming equivalent of monad like sequenced application of
3697-- parsers where next parser is dependent on the previous parser.
3701{-# INLINE parseIterate #-}
3703 :: (IsStream t, MonadThrow m)
3704 => (b -> Parser m a b)
3708parseIterate f i m = D.fromStreamD $
3709 D.parseIterate (PRK.fromParserK . f) i (D.toStreamD m)
3711------------------------------------------------------------------------------
3712-- Grouping/Splitting
3713------------------------------------------------------------------------------
3715------------------------------------------------------------------------------
3716-- Grouping without looking at elements
3717------------------------------------------------------------------------------
3719------------------------------------------------------------------------------
3721------------------------------------------------------------------------------
3724------------------------------------------------------------------------------
3726------------------------------------------------------------------------------
3728------------------------------------------------------------------------------
3729-- Generalized grouping
3730------------------------------------------------------------------------------
3732-- This combinator is the most general grouping combinator and can be used to
3733-- implement all other grouping combinators.
3735-- XXX check if this can implement the splitOn combinator i.e. we can slide in
3736-- new elements, slide out old elements and incrementally compute the hash.
3737-- Also, can we implement the windowed classification combinators using this?
3739-- In fact this is a parse. Instead of using a special return value in the fold
3740-- we are using a mapping function.
3742-- Note that 'scanl'' (usually followed by a map to extract the desired value
3743-- from the accumulator) can be used to realize many implementations e.g. a
3744-- sliding window implementation. A scan followed by a mapMaybe is also a good
3745-- pattern to express many problems where we want to emit a filtered output and
3746-- not emit an output on every input.
3748-- Passing on of the initial accumulator value to the next fold is equivalent
3749-- to returning the leftover concept.
3752-- | @groupScan splitter fold stream@ folds the input stream using @fold@.
3753-- @splitter@ is applied on the accumulator of the fold every time an item is
3754-- consumed by the fold. The fold continues until @splitter@ returns a 'Just'
3755-- value. A 'Just' result from the @splitter@ specifies a result to be emitted
3756-- in the output stream and the initial value of the accumulator for the next
3757-- group's fold. This allows us to control whether to start fresh for the next
3758-- fold or to continue from the previous fold's output.
3760{-# INLINE groupScan #-}
3762 :: (IsStream t, Monad m)
3763 => (x -> m (Maybe (b, x))) -> Fold m a x -> t m a -> t m b
3764groupScan split fold m = undefined
3767-- | Group the input stream into groups of @n@ elements each and then fold each
3768-- group using the provided fold function.
3770-- >> S.toList $ S.chunksOf 2 FL.sum (S.enumerateFromTo 1 10)
3773-- This can be considered as an n-fold version of 'ltake' where we apply
3774-- 'ltake' repeatedly on the leftover stream until the stream exhausts.
3777{-# INLINE chunksOf #-}
3779 :: (IsStream t, Monad m)
3780 => Int -> Fold m a b -> t m a -> t m b
3781chunksOf n f m = D.fromStreamD $ D.groupsOf n f (D.toStreamD m)
3786{-# INLINE chunksOf2 #-}
3788 :: (IsStream t, Monad m)
3789 => Int -> m c -> Fold2 m c a b -> t m a -> t m b
3790chunksOf2 n action f m = D.fromStreamD $ D.groupsOf2 n action f (D.toStreamD m)
3792-- | @arraysOf n stream@ groups the elements in the input stream into arrays of
3793-- @n@ elements each.
3795-- Same as the following but may be more efficient:
3797-- > arraysOf n = S.chunksOf n (A.writeN n)
3800{-# INLINE arraysOf #-}
3801arraysOf :: (IsStream t, MonadIO m, Storable a)
3802 => Int -> t m a -> t m (Array a)
3803arraysOf n = chunksOf n (writeNUnsafe n)
3805-- XXX we can implement this by repeatedly applying the 'lrunFor' fold.
3806-- XXX add this example after fixing the serial stream rate control
3807-- >>> S.toList $ S.take 5 $ intervalsOf 1 FL.sum $ constRate 2 $ S.enumerateFrom 1
3810-- | Group the input stream into windows of @n@ second each and then fold each
3811-- group using the provided fold function.
3814{-# INLINE intervalsOf #-}
3816 :: (IsStream t, MonadAsync m)
3817 => Double -> Fold m a b -> t m a -> t m b
3819 splitWithSuffix isNothing (FL.lcatMaybes f)
3820 (interjectSuffix n (return Nothing) (Serial.map Just xs))
3822------------------------------------------------------------------------------
3824------------------------------------------------------------------------------
3826-- | @groupsBy cmp f $ S.fromList [a,b,c,...]@ assigns the element @a@ to the
3827-- first group, if @b \`cmp` a@ is 'True' then @b@ is also assigned to the same
3828-- group. If @c \`cmp` a@ is 'True' then @c@ is also assigned to the same
3829-- group and so on. When the comparison fails a new group is started. Each
3830-- group is folded using the fold @f@ and the result of the fold is emitted in
3831-- the output stream.
3833-- >>> S.toList $ S.groupsBy (>) FL.toList $ S.fromList [1,3,7,0,2,5]
3834-- > [[1,3,7],[0,2,5]]
3837{-# INLINE groupsBy #-}
3839 :: (IsStream t, Monad m)
3844groupsBy cmp f m = D.fromStreamD $ D.groupsBy cmp f (D.toStreamD m)
3846-- | Unlike @groupsBy@ this function performs a rolling comparison of two
3847-- successive elements in the input stream. @groupsByRolling cmp f $ S.fromList
3848-- [a,b,c,...]@ assigns the element @a@ to the first group, if @a \`cmp` b@ is
3849-- 'True' then @b@ is also assigned to the same group. If @b \`cmp` c@ is
3850-- 'True' then @c@ is also assigned to the same group and so on. When the
3851-- comparison fails a new group is started. Each group is folded using the fold
3854-- >>> S.toList $ S.groupsByRolling (\a b -> a + 1 == b) FL.toList $ S.fromList [1,2,3,7,8,9]
3855-- > [[1,2,3],[7,8,9]]
3858{-# INLINE groupsByRolling #-}
3860 :: (IsStream t, Monad m)
3865groupsByRolling cmp f m = D.fromStreamD $ D.groupsRollingBy cmp f (D.toStreamD m)
3868-- > groups = groupsBy (==)
3869-- > groups = groupsByRolling (==)
3871-- Groups contiguous spans of equal elements together in individual groups.
3873-- >>> S.toList $ S.groups FL.toList $ S.fromList [1,1,2,2]
3877groups :: (IsStream t, Monad m, Eq a) => Fold m a b -> t m a -> t m b
3878groups = groupsBy (==)
3880------------------------------------------------------------------------------
3881-- N-ary split on a predicate
3882------------------------------------------------------------------------------
3884-- TODO: Use a Splitter configuration similar to the "split" package to make it
3885-- possible to express all splitting combinations. In general, we can have
3886-- infix/suffix/prefix/condensing of separators, dropping both leading/trailing
3887-- separators. We can have a single split operation taking the splitter config
3890-- | Split on an infixed separator element, dropping the separator. Splits the
3891-- stream on separator elements determined by the supplied predicate, separator
3892-- is considered as infixed between two segments, if one side of the separator
3893-- is missing then it is parsed as an empty stream. The supplied 'Fold' is
3894-- applied on the split segments. With '-' representing non-separator elements
3895-- and '.' as separator, 'splitOn' splits as follows:
3898-- "--.--" => "--" "--"
3903-- @splitOn (== x)@ is an inverse of @intercalate (S.yield x)@
3905-- Let's use the following definition for illustration:
3907-- > splitOn' p xs = S.toList $ S.splitOn p (FL.toList) (S.fromList xs)
3909-- >>> splitOn' (== '.') ""
3912-- >>> splitOn' (== '.') "."
3915-- >>> splitOn' (== '.') ".a"
3918-- >>> splitOn' (== '.') "a."
3921-- >>> splitOn' (== '.') "a.b"
3924-- >>> splitOn' (== '.') "a..b"
3929-- This can be considered as an n-fold version of 'breakOn' where we apply
3930-- 'breakOn' successively on the input stream, dropping the first element
3931-- of the second segment after each break.
3933{-# INLINE splitOn #-}
3935 :: (IsStream t, Monad m)
3936 => (a -> Bool) -> Fold m a b -> t m a -> t m b
3937splitOn predicate f m =
3938 D.fromStreamD $ D.splitBy predicate f (D.toStreamD m)
3940-- | Like 'splitOn' but the separator is considered as suffixed to the segments
3941-- in the stream. A missing suffix at the end is allowed. A separator at the
3942-- beginning is parsed as empty segment. With '-' representing elements and
3943-- '.' as separator, 'splitOnSuffix' splits as follows:
3946-- "--.--." => "--" "--"
3947-- "--.--" => "--" "--"
3951-- > splitOnSuffix' p xs = S.toList $ S.splitSuffixBy p (FL.toList) (S.fromList xs)
3953-- >>> splitOnSuffix' (== '.') ""
3956-- >>> splitOnSuffix' (== '.') "."
3959-- >>> splitOnSuffix' (== '.') "a"
3962-- >>> splitOnSuffix' (== '.') ".a"
3965-- >>> splitOnSuffix' (== '.') "a."
3968-- >>> splitOnSuffix' (== '.') "a.b"
3971-- >>> splitOnSuffix' (== '.') "a.b."
3974-- >>> splitOnSuffix' (== '.') "a..b.."
3977-- > lines = splitOnSuffix (== '\n')
3981-- This can be considered as an n-fold version of 'breakPost' where we apply
3982-- 'breakPost' successively on the input stream, dropping the first element
3983-- of the second segment after each break.
3985{-# INLINE splitOnSuffix #-}
3987 :: (IsStream t, Monad m)
3988 => (a -> Bool) -> Fold m a b -> t m a -> t m b
3989splitOnSuffix predicate f m =
3990 D.fromStreamD $ D.splitSuffixBy predicate f (D.toStreamD m)
3992-- | Like 'splitOn' after stripping leading, trailing, and repeated separators.
3993-- Therefore, @".a..b."@ with '.' as the separator would be parsed as
3994-- @["a","b"]@. In other words, its like parsing words from whitespace
3997-- > wordsBy' p xs = S.toList $ S.wordsBy p (FL.toList) (S.fromList xs)
3999-- >>> wordsBy' (== ',') ""
4002-- >>> wordsBy' (== ',') ","
4005-- >>> wordsBy' (== ',') ",a,,b,"
4008-- > words = wordsBy isSpace
4012-- It is equivalent to splitting in any of the infix/prefix/suffix styles
4013-- followed by removal of empty segments.
4014{-# INLINE wordsBy #-}
4016 :: (IsStream t, Monad m)
4017 => (a -> Bool) -> Fold m a b -> t m a -> t m b
4018wordsBy predicate f m =
4019 D.fromStreamD $ D.wordsBy predicate f (D.toStreamD m)
4021-- | Like 'splitOnSuffix' but keeps the suffix attached to the resulting
4024-- > splitWithSuffix' p xs = S.toList $ S.splitWithSuffix p (FL.toList) (S.fromList xs)
4026-- >>> splitWithSuffix' (== '.') ""
4029-- >>> splitWithSuffix' (== '.') "."
4032-- >>> splitWithSuffix' (== '.') "a"
4035-- >>> splitWithSuffix' (== '.') ".a"
4038-- >>> splitWithSuffix' (== '.') "a."
4041-- >>> splitWithSuffix' (== '.') "a.b"
4044-- >>> splitWithSuffix' (== '.') "a.b."
4047-- >>> splitWithSuffix' (== '.') "a..b.."
4048-- > ["a.",".","b.","."]
4052-- This can be considered as an n-fold version of 'breakPost' where we apply
4053-- 'breakPost' successively on the input stream.
4055{-# INLINE splitWithSuffix #-}
4057 :: (IsStream t, Monad m)
4058 => (a -> Bool) -> Fold m a b -> t m a -> t m b
4059splitWithSuffix predicate f m =
4060 D.fromStreamD $ D.splitSuffixBy' predicate f (D.toStreamD m)
4062------------------------------------------------------------------------------
4063-- Split on a delimiter sequence
4064------------------------------------------------------------------------------
4066-- Int list examples for splitOn:
4068-- >>> splitList [] [1,2,3,3,4]
4069-- > [[1],[2],[3],[3],[4]]
4071-- >>> splitList [5] [1,2,3,3,4]
4074-- >>> splitList [1] [1,2,3,3,4]
4077-- >>> splitList [4] [1,2,3,3,4]
4080-- >>> splitList [2] [1,2,3,3,4]
4083-- >>> splitList [3] [1,2,3,3,4]
4086-- >>> splitList [3,3] [1,2,3,3,4]
4089-- >>> splitList [1,2,3,3,4] [1,2,3,3,4]
4092-- | Like 'splitOn' but the separator is a sequence of elements instead of a
4095-- For illustration, let's define a function that operates on pure lists:
4098-- splitOnSeq' pat xs = S.toList $ S.splitOnSeq (A.fromList pat) (FL.toList) (S.fromList xs)
4101-- >>> splitOnSeq' "" "hello"
4102-- > ["h","e","l","l","o"]
4104-- >>> splitOnSeq' "hello" ""
4107-- >>> splitOnSeq' "hello" "hello"
4110-- >>> splitOnSeq' "x" "hello"
4113-- >>> splitOnSeq' "h" "hello"
4116-- >>> splitOnSeq' "o" "hello"
4119-- >>> splitOnSeq' "e" "hello"
4122-- >>> splitOnSeq' "l" "hello"
4125-- >>> splitOnSeq' "ll" "hello"
4128-- 'splitOnSeq' is an inverse of 'intercalate'. The following law always holds:
4130-- > intercalate . splitOn == id
4132-- The following law holds when the separator is non-empty and contains none of
4133-- the elements present in the input lists:
4135-- > splitOn . intercalate == id
4139-- XXX We can use a polymorphic vector implemented by Array# to represent the
4140-- sequence, that way we can avoid the Storable constraint. If we still need
4141-- Storable Array for performance, we can use a separate splitOnArray API for
4142-- that. We can also have an API where the sequence itself is a lazy stream, so
4143-- that we can search files in files for example.
4144{-# INLINE splitOnSeq #-}
4146 :: (IsStream t, MonadIO m, Storable a, Enum a, Eq a)
4147 => Array a -> Fold m a b -> t m a -> t m b
4148splitOnSeq patt f m = D.fromStreamD $ D.splitOn patt f (D.toStreamD m)
4151-- This can be implemented easily using Rabin Karp
4152-- | Split on any one of the given patterns.
4153{-# INLINE splitOnAny #-}
4155 :: (IsStream t, Monad m, Storable a, Integral a)
4156 => [Array a] -> Fold m a b -> t m a -> t m b
4157splitOnAny subseq f m = undefined -- D.fromStreamD $ D.splitOnAny f subseq (D.toStreamD m)
4160-- | Like 'splitSuffixBy' but the separator is a sequence of elements, instead
4161-- of a predicate for a single element.
4163-- > splitSuffixOn_ pat xs = S.toList $ S.splitSuffixOn (A.fromList pat) (FL.toList) (S.fromList xs)
4165-- >>> splitSuffixOn_ "." ""
4168-- >>> splitSuffixOn_ "." "."
4171-- >>> splitSuffixOn_ "." "a"
4174-- >>> splitSuffixOn_ "." ".a"
4177-- >>> splitSuffixOn_ "." "a."
4180-- >>> splitSuffixOn_ "." "a.b"
4183-- >>> splitSuffixOn_ "." "a.b."
4186-- >>> splitSuffixOn_ "." "a..b.."
4189-- > lines = splitSuffixOn "\n"
4192{-# INLINE splitOnSuffixSeq #-}
4194 :: (IsStream t, MonadIO m, Storable a, Enum a, Eq a)
4195 => Array a -> Fold m a b -> t m a -> t m b
4196splitOnSuffixSeq patt f m =
4197 D.fromStreamD $ D.splitSuffixOn False patt f (D.toStreamD m)
4200-- | Like 'splitOn' but drops any empty splits.
4202{-# INLINE wordsOn #-}
4204 :: (IsStream t, Monad m, Storable a, Eq a)
4205 => Array a -> Fold m a b -> t m a -> t m b
4206wordsOn subseq f m = undefined -- D.fromStreamD $ D.wordsOn f subseq (D.toStreamD m)
4209-- XXX use a non-monadic intersperse to remove the MonadAsync constraint.
4211-- | Like 'splitOnSeq' but splits the separator as well, as an infix token.
4213-- > splitOn'_ pat xs = S.toList $ S.splitOn' (A.fromList pat) (FL.toList) (S.fromList xs)
4215-- >>> splitOn'_ "" "hello"
4216-- > ["h","","e","","l","","l","","o"]
4218-- >>> splitOn'_ "hello" ""
4221-- >>> splitOn'_ "hello" "hello"
4224-- >>> splitOn'_ "x" "hello"
4227-- >>> splitOn'_ "h" "hello"
4230-- >>> splitOn'_ "o" "hello"
4233-- >>> splitOn'_ "e" "hello"
4236-- >>> splitOn'_ "l" "hello"
4237-- > ["he","l","","l","o"]
4239-- >>> splitOn'_ "ll" "hello"
4243{-# INLINE splitBySeq #-}
4245 :: (IsStream t, MonadAsync m, Storable a, Enum a, Eq a)
4246 => Array a -> Fold m a b -> t m a -> t m b
4247splitBySeq patt f m =
4248 intersperseM (fold f (A.toStream patt)) $ splitOnSeq patt f m
4250-- | Like 'splitSuffixOn' but keeps the suffix intact in the splits.
4252-- > splitSuffixOn'_ pat xs = S.toList $ FL.splitSuffixOn' (A.fromList pat) (FL.toList) (S.fromList xs)
4254-- >>> splitSuffixOn'_ "." ""
4257-- >>> splitSuffixOn'_ "." "."
4260-- >>> splitSuffixOn'_ "." "a"
4263-- >>> splitSuffixOn'_ "." ".a"
4266-- >>> splitSuffixOn'_ "." "a."
4269-- >>> splitSuffixOn'_ "." "a.b"
4272-- >>> splitSuffixOn'_ "." "a.b."
4275-- >>> splitSuffixOn'_ "." "a..b.."
4276-- > ["a.",".","b.","."]
4279{-# INLINE splitWithSuffixSeq #-}
4281 :: (IsStream t, MonadIO m, Storable a, Enum a, Eq a)
4282 => Array a -> Fold m a b -> t m a -> t m b
4283splitWithSuffixSeq patt f m =
4284 D.fromStreamD $ D.splitSuffixOn True patt f (D.toStreamD m)
4287-- This can be implemented easily using Rabin Karp
4288-- | Split post any one of the given patterns.
4289{-# INLINE splitSuffixOnAny #-}
4291 :: (IsStream t, Monad m, Storable a, Integral a)
4292 => [Array a] -> Fold m a b -> t m a -> t m b
4293splitSuffixOnAny subseq f m = undefined
4294 -- D.fromStreamD $ D.splitPostAny f subseq (D.toStreamD m)
4297------------------------------------------------------------------------------
4299------------------------------------------------------------------------------
4301-- | @splitInnerBy splitter joiner stream@ splits the inner containers @f a@ of
4302-- an input stream @t m (f a)@ using the @splitter@ function. Container
4303-- elements @f a@ are collected until a split occurs, then all the elements
4304-- before the split are joined using the @joiner@ function.
4306-- For example, if we have a stream of @Array Word8@, we may want to split the
4307-- stream into arrays representing lines separated by '\n' byte such that the
4308-- resulting stream after a split would be one array for each line.
4310-- CAUTION! This is not a true streaming function as the container size after
4311-- the split and merge may not be bounded.
4314{-# INLINE splitInnerBy #-}
4316 :: (IsStream t, Monad m)
4317 => (f a -> m (f a, Maybe (f a))) -- splitter
4318 -> (f a -> f a -> m (f a)) -- joiner
4321splitInnerBy splitter joiner xs =
4322 D.fromStreamD $ D.splitInnerBy splitter joiner $ D.toStreamD xs
4324-- | Like 'splitInnerBy' but splits assuming the separator joins the segment in
4328{-# INLINE splitInnerBySuffix #-}
4330 :: (IsStream t, Monad m, Eq (f a), Monoid (f a))
4331 => (f a -> m (f a, Maybe (f a))) -- splitter
4332 -> (f a -> f a -> m (f a)) -- joiner
4335splitInnerBySuffix splitter joiner xs =
4336 D.fromStreamD $ D.splitInnerBySuffix splitter joiner $ D.toStreamD xs
4338------------------------------------------------------------------------------
4339-- Reorder in sequence
4340------------------------------------------------------------------------------
4343-- Buffer until the next element in sequence arrives. The function argument
4344-- determines the difference in sequence numbers. This could be useful in
4345-- implementing sequenced streams, for example, TCP reassembly.
4346{-# INLINE reassembleBy #-}
4348 :: (IsStream t, Monad m)
4353reassembleBy = undefined
4356------------------------------------------------------------------------------
4358------------------------------------------------------------------------------
4360-- | Tap the data flowing through a stream into a 'Fold'. For example, you may
4361-- add a tap to log the contents flowing through the stream. The fold is used
4362-- only for effects, its result is discarded.
4367-- -----stream m a ---------------stream m a-----
4372-- > S.drain $ S.tap (FL.drainBy print) (S.enumerateFromTo 1 2)
4377-- Compare with 'trace'.
4381tap :: (IsStream t, Monad m) => FL.Fold m a b -> t m a -> t m a
4382tap f xs = D.fromStreamD $ D.tap f (D.toStreamD xs)
4384-- | @tapOffsetEvery offset n@ taps every @n@th element in the stream
4385-- starting at @offset@. @offset@ can be between @0@ and @n - 1@. Offset 0
4386-- means start at the first element in the stream. If the offset is outside
4387-- this range then @offset `mod` n@ is used as offset.
4390-- >>> S.drain $ S.tapOffsetEvery 0 2 (FL.mapM print FL.toList) $ S.enumerateFromTo 0 10
4396{-# INLINE tapOffsetEvery #-}
4397tapOffsetEvery :: (IsStream t, Monad m)
4398 => Int -> Int -> FL.Fold m a b -> t m a -> t m a
4399tapOffsetEvery offset n f xs =
4400 D.fromStreamD $ D.tapOffsetEvery offset n f (D.toStreamD xs)
4402-- | Redirect a copy of the stream to a supplied fold and run it concurrently
4403-- in an independent thread. The fold may buffer some elements. The buffer size
4404-- is determined by the prevailing 'maxBuffer' setting.
4409-- -----stream m a ---------------stream m a-----
4414-- > S.drain $ S.tapAsync (S.mapM_ print) (S.enumerateFromTo 1 2)
4419-- Exceptions from the concurrently running fold are propagated to the current
4420-- computation. Note that, because of buffering in the fold, exceptions may be
4421-- delayed and may not correspond to the current element being processed in the
4422-- parent stream, but we guarantee that before the parent stream stops the tap
4423-- finishes and all exceptions from it are drained.
4426-- Compare with 'tap'.
4429{-# INLINE tapAsync #-}
4430tapAsync :: (IsStream t, MonadAsync m) => FL.Fold m a b -> t m a -> t m a
4431tapAsync f xs = D.fromStreamD $ D.tapAsync f (D.toStreamD xs)
4433-- | @pollCounts predicate transform fold stream@ counts those elements in the
4434-- stream that pass the @predicate@. The resulting count stream is sent to
4435-- another thread which transforms it using @transform@ and then folds it using
4436-- @fold@. The thread is automatically cleaned up if the stream stops or
4437-- aborts due to exception.
4439-- For example, to print the count of elements processed every second:
4442-- > S.drain $ S.pollCounts (const True) (S.rollingMap (-) . S.delayPost 1) (FL.drainBy print)
4443-- $ S.enumerateFrom 0
4446-- Note: This may not work correctly on 32-bit machines.
4450{-# INLINE pollCounts #-}
4452 (IsStream t, MonadAsync m)
4454 -> (t m Int -> t m Int)
4458pollCounts predicate transf f xs =
4460 $ D.pollCounts predicate (D.toStreamD . transf . D.fromStreamD) f
4463-- | Calls the supplied function with the number of elements consumed
4464-- every @n@ seconds. The given function is run in a separate thread
4465-- until the end of the stream. In case there is an exception in the
4466-- stream the thread is killed during the next major GC.
4468-- Note: The action is not guaranteed to run if the main thread exits.
4471-- > delay n = threadDelay (round $ n * 1000000) >> return n
4472-- > S.drain $ S.tapRate 2 (\\n -> print $ show n ++ " elements processed") (delay 1 S.|: delay 0.5 S.|: delay 0.5 S.|: S.nil)
4473-- 2 elements processed
4474-- 1 elements processed
4477-- Note: This may not work correctly on 32-bit machines.
4480{-# INLINE tapRate #-}
4482 (IsStream t, MonadAsync m, MonadCatch m)
4487tapRate n f xs = D.fromStreamD $ D.tapRate n f $ D.toStreamD xs
4489-- | Apply a monadic function to each element flowing through the stream and
4490-- discard the results.
4493-- > S.drain $ S.trace print (S.enumerateFromTo 1 2)
4498-- Compare with 'tap'.
4502trace :: (IsStream t, MonadAsync m) => (a -> m b) -> t m a -> t m a
4503trace f = mapM (\x -> void (f x) >> return x)
4505-- | Perform a side effect before yielding each element of the stream and
4506-- discard the results.
4509-- > S.drain $ S.trace_ (print "got here") (S.enumerateFromTo 1 2)
4514-- See also: 'trace', 'interspersePrefix_'
4517{-# INLINE trace_ #-}
4518trace_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
4519trace_ eff = Serial.mapM (\x -> eff >> return x)
4521------------------------------------------------------------------------------
4522-- Windowed classification
4523------------------------------------------------------------------------------
4525-- We divide the stream into windows or chunks in space or time and each window
4526-- can be associated with a key, all events associated with a particular key in
4527-- the window can be folded to a single result. The stream can be split into
4528-- windows by size or by using a split predicate on the elements in the stream.
4529-- For example, when we receive a closing flag, we can close the window.
4531-- A "chunk" is a space window and a "session" is a time window. Are there any
4532-- other better short words to describe them. An alternative is to use
4533-- "swindow" and "twindow". Another word for "session" could be "spell".
4535-- TODO: To mark the position in space or time we can have Indexed or
4536-- TimeStamped types. That can make it easy to deal with the position indices
4539------------------------------------------------------------------------------
4540-- Keyed Sliding Windows
4541------------------------------------------------------------------------------
4544{-# INLINABLE classifySlidingChunks #-}
4545classifySlidingChunks
4546 :: (IsStream t, MonadAsync m, Ord k)
4547 => Int -- ^ window size
4548 -> Int -- ^ window slide
4549 -> Fold m a b -- ^ Fold to be applied to window events
4550 -> t m (k, a, Bool) -- ^ window key, data, close event
4552classifySlidingChunks wsize wslide (Fold step initial extract) str
4555-- XXX Another variant could be to slide the window on an event, e.g. in TCP we
4556-- slide the send window when an ack is received and we slide the receive
4557-- window when a sequence is complete. Sliding is stateful in case of TCP,
4558-- sliding releases the send buffer or makes data available to the user from
4559-- the receive buffer.
4560{-# INLINABLE classifySlidingSessions #-}
4561classifySlidingSessions
4562 :: (IsStream t, MonadAsync m, Ord k)
4563 => Double -- ^ timer tick in seconds
4564 -> Double -- ^ time window size
4565 -> Double -- ^ window slide
4566 -> Fold m a b -- ^ Fold to be applied to window events
4567 -> t m (k, a, Bool, AbsTime) -- ^ window key, data, close flag, timestamp
4569classifySlidingSessions tick interval slide (Fold step initial extract) str
4573------------------------------------------------------------------------------
4574-- Sliding Window Buffers
4575------------------------------------------------------------------------------
4577-- These buffered versions could be faster than concurrent incremental folds of
4578-- all overlapping windows as in many cases we may not need all the values to
4579-- compute the fold, we can just compute the result using the old value and new
4580-- value. However, we may need the buffer once in a while, for example for
4581-- string search we usually compute the hash incrementally but when the hash
4582-- matches the hash of the pattern we need to compare the whole string.
4584-- XXX we should be able to implement sequence based splitting combinators
4585-- using this combinator.
4588-- | Buffer n elements of the input in a ring buffer. When t new elements are
4589-- collected, slide the window to remove the same number of oldest elements,
4590-- insert the new elements, and apply an incremental fold on the sliding
4591-- window, supplying the outgoing elements, the new ring buffer as arguments.
4593 :: (IsStream t, Monad m, Ord a, Storable a)
4594 => Int -- window size
4595 -> Int -- window slide
4596 -> Fold m (Ring a, Array a) b
4599slidingChunkBuffer = undefined
4601-- Buffer n seconds worth of stream elements of the input in a radix tree.
4602-- Every t seconds, remove the items that are older than n seconds, and apply
4603-- an incremental fold on the sliding window, supplying the outgoing elements,
4604-- and the new radix tree buffer as arguments.
4606 :: (IsStream t, Monad m, Ord a, Storable a)
4607 => Int -- window size
4609 -> Fold m (RTree a, Array a) b
4612slidingSessionBuffer = undefined
4615------------------------------------------------------------------------------
4616-- Keyed Session Windows
4617------------------------------------------------------------------------------
4620-- | Keyed variable size space windows. Close the window if we do not receive a
4621-- window event in the next "spaceout" elements.
4622{-# INLINABLE classifyChunksBy #-}
4624 :: (IsStream t, MonadAsync m, Ord k)
4625 => Int -- ^ window spaceout (spread)
4626 -> Bool -- ^ reset the spaceout when a chunk window element is received
4627 -> Fold m a b -- ^ Fold to be applied to chunk window elements
4628 -> t m (k, a, Bool) -- ^ chunk key, data, last element
4630classifyChunksBy spanout reset (Fold step initial extract) str = undefined
4632-- | Like 'classifyChunksOf' but the chunk size is reset if an element is
4633-- received within the chunk size window. The chunk gets closed only if no
4634-- element is received within the chunk window.
4636{-# INLINABLE classifyKeepAliveChunks #-}
4637classifyKeepAliveChunks
4638 :: (IsStream t, MonadAsync m, Ord k)
4639 => Int -- ^ window spaceout (spread)
4640 -> Fold m a b -- ^ Fold to be applied to chunk window elements
4641 -> t m (k, a, Bool) -- ^ chunk key, data, last element
4643classifyKeepAliveChunks spanout = classifyChunksBy spanout True
4646data SessionState t m k a b = SessionState
4647 { sessionCurTime :: !AbsTime -- ^ time since last event
4648 , sessionEventTime :: !AbsTime -- ^ time as per last event
4649 , sessionCount :: !Int -- ^ total number sessions in progress
4650 , sessionTimerHeap :: H.Heap (H.Entry AbsTime k) -- ^ heap for timeouts
4651 , sessionKeyValueMap :: Map.Map k a -- ^ Stored sessions for keys
4652 , sessionOutputStream :: t (m :: Type -> Type) (k, b) -- ^ Completed sessions
4657-- | @classifySessionsBy tick timeout idle pred f stream@ groups timestamped
4658-- events in an input event stream into sessions based on a session key. Each
4659-- element in the stream is an event consisting of a triple @(session key,
4660-- sesssion data, timestamp)@. @session key@ is a key that uniquely identifies
4661-- the session. All the events belonging to a session are folded using the
4662-- fold @f@ until the fold returns a 'Left' result or a timeout has occurred.
4663-- The session key and the result of the fold are emitted in the output stream
4664-- when the session is purged.
4666-- When @idle@ is 'False', @timeout@ is the maximum lifetime of a session in
4667-- seconds, measured from the @timestamp@ of the first event in that session.
4668-- When @idle@ is 'True' then the timeout is an idle timeout, it is reset after
4669-- every event received in the session.
4671-- @timestamp@ in an event characterizes the time when the input event was
4672-- generated, this is an absolute time measured from some @Epoch@. The notion
4673-- of current time is maintained by a monotonic event time clock using the
4674-- timestamps seen in the input stream. The latest timestamp seen till now is
4675-- used as the base for the current time. When no new events are seen, a timer
4676-- is started with a tick duration specified by @tick@. This timer is used to
4677-- detect session timeouts in the absence of new events.
4679-- The predicate @pred@ is invoked with the current session count, if it
4680-- returns 'True' a session is ejected from the session cache before inserting
4681-- a new session. This could be useful to alert or eject sessions when the
4682-- number of sessions becomes too high.
4687-- XXX Perhaps we should use an "Event a" type to represent timestamped data.
4688{-# INLINABLE classifySessionsBy #-}
4690 :: (IsStream t, MonadAsync m, Ord k)
4691 => Double -- ^ timer tick in seconds
4692 -> Double -- ^ session timeout in seconds
4693 -> Bool -- ^ reset the timeout when an event is received
4694 -> (Int -> m Bool) -- ^ predicate to eject sessions based on session count
4695 -> Fold m a (Either b b) -- ^ Fold to be applied to session events
4696 -> t m (k, a, AbsTime) -- ^ session key, data, timestamp
4697 -> t m (k, b) -- ^ session key, fold result
4698classifySessionsBy tick tmout reset ejectPred
4699 (Fold step initial extract) str =
4700 concatMap sessionOutputStream $
4701 scanlMAfter' sstep (return szero) flush stream
4705 timeoutMs = toRelTime (round (tmout * 1000) :: MilliSecond64)
4706 tickMs = toRelTime (round (tick * 1000) :: MilliSecond64)
4707 szero = SessionState
4708 { sessionCurTime = toAbsTime (0 :: MilliSecond64)
4709 , sessionEventTime = toAbsTime (0 :: MilliSecond64)
4711 , sessionTimerHeap = H.empty
4712 , sessionKeyValueMap = Map.empty
4713 , sessionOutputStream = K.nil
4716 -- We can eject sessions based on the current session count to limit
4717 -- memory consumption. There are two possible strategies:
4719 -- 1) Eject old sessions or sessions beyond a certain/lower timeout
4720 -- threshold even before timeout, effectively reduce the timeout.
4721 -- 2) Drop creation of new sessions but keep accepting new events for the
4724 -- We use the first strategy as of now.
4726 -- Got a new stream input element
4727 sstep session@SessionState{..} (Just (key, value, timestamp)) = do
4728 -- XXX we should use a heap in pinned memory to scale it to a large
4731 -- To detect session inactivity we keep a timestamp of the latest event
4732 -- in the Map along with the fold result. When we purge the session
4733 -- from the heap we match the timestamp in the heap with the timestamp
4734 -- in the Map, if the latest timestamp is newer and has not expired we
4735 -- reinsert the key in the heap.
4737 -- XXX if the key is an Int, we can also use an IntMap for slightly
4738 -- better performance.
4740 let curTime = max sessionEventTime timestamp
4744 Just (Tuple' _ acc) -> return acc
4745 new <- step old value
4746 return $ Tuple' timestamp new
4747 mOld = Map.lookup key sessionKeyValueMap
4749 acc@(Tuple' _ fres) <- accumulate mOld
4753 -- deleting a key from the heap is expensive, so we never
4754 -- delete a key from heap, we just purge it from the Map and it
4755 -- gets purged from the heap on timeout. We just need an extra
4756 -- lookup in the Map when the key is purged from the heap, that
4757 -- should not be expensive.
4759 let (mp, cnt) = case mOld of
4760 Nothing -> (sessionKeyValueMap, sessionCount)
4761 Just _ -> (Map.delete key sessionKeyValueMap
4764 { sessionCurTime = curTime
4765 , sessionEventTime = curTime
4766 , sessionCount = cnt
4767 , sessionKeyValueMap = mp
4768 , sessionOutputStream = yield (key, x)
4771 (hp1, mp1, out1, cnt1) <- do
4772 let vars = (sessionTimerHeap, sessionKeyValueMap,
4773 K.nil, sessionCount)
4775 -- inserting new entry
4777 -- Eject a session from heap and map is needed
4778 eject <- ejectPred sessionCount
4779 (hp, mp, out, cnt) <-
4784 -- Insert the new session in heap
4785 let expiry = addToAbsTime timestamp timeoutMs
4786 hp' = H.insert (Entry expiry key) hp
4787 in return (hp', mp, out, cnt + 1)
4788 -- updating old entry
4789 Just _ -> return vars
4791 let mp2 = Map.insert key acc mp1
4792 return $ SessionState
4793 { sessionCurTime = curTime
4794 , sessionEventTime = curTime
4795 , sessionCount = cnt1
4796 , sessionTimerHeap = hp1
4797 , sessionKeyValueMap = mp2
4798 , sessionOutputStream = out1
4801 -- Got a timer tick event
4802 sstep sessionState@SessionState{..} Nothing =
4803 let curTime = addToAbsTime sessionCurTime tickMs
4804 in ejectExpired sessionState curTime
4806 flush session@SessionState{..} = do
4807 (hp', mp', out, count) <-
4810 , sessionKeyValueMap
4815 { sessionCount = count
4816 , sessionTimerHeap = hp'
4817 , sessionKeyValueMap = mp'
4818 , sessionOutputStream = out
4826 -- delete from map and output the fold accumulator
4827 ejectEntry hp mp out cnt acc key = do
4829 let out1 = (key, fromEither sess) `K.cons` out
4830 let mp1 = Map.delete key mp
4831 return (hp, mp1, out1, cnt - 1)
4833 ejectAll (hp, mp, out, !cnt) = do
4834 let hres = H.uncons hp
4836 Just (Entry _ key, hp1) -> do
4837 r <- case Map.lookup key mp of
4838 Nothing -> return (hp1, mp, out, cnt)
4839 Just (Tuple' _ acc) -> ejectEntry hp1 mp out cnt acc key
4842 assert (Map.null mp) (return ())
4843 return (hp, mp, out, cnt)
4845 ejectOne (hp, mp, out, !cnt) = do
4846 let hres = H.uncons hp
4848 Just (Entry expiry key, hp1) ->
4849 case Map.lookup key mp of
4850 Nothing -> ejectOne (hp1, mp, out, cnt)
4851 Just (Tuple' latestTS acc) -> do
4852 let expiry1 = addToAbsTime latestTS timeoutMs
4853 if not reset || expiry1 <= expiry
4854 then ejectEntry hp1 mp out cnt acc key
4856 -- reset the session timeout and continue
4857 let hp2 = H.insert (Entry expiry1 key) hp1
4858 in ejectOne (hp2, mp, out, cnt)
4860 assert (Map.null mp) (return ())
4861 return (hp, mp, out, cnt)
4863 ejectExpired session@SessionState{..} curTime = do
4864 (hp', mp', out, count) <-
4865 ejectLoop sessionTimerHeap sessionKeyValueMap K.nil sessionCount
4867 { sessionCurTime = curTime
4868 , sessionCount = count
4869 , sessionTimerHeap = hp'
4870 , sessionKeyValueMap = mp'
4871 , sessionOutputStream = out
4876 ejectLoop hp mp out !cnt = do
4877 let hres = H.uncons hp
4879 Just (Entry expiry key, hp1) -> do
4881 if curTime >= expiry
4882 then return (True, False)
4888 case Map.lookup key mp of
4889 Nothing -> ejectLoop hp1 mp out cnt
4890 Just (Tuple' latestTS acc) -> do
4891 let expiry1 = addToAbsTime latestTS timeoutMs
4892 if expiry1 <= curTime || not reset || force
4894 (hp2,mp1,out1,cnt1) <-
4895 ejectEntry hp1 mp out cnt acc key
4896 ejectLoop hp2 mp1 out1 cnt1
4898 -- reset the session timeout and continue
4899 let hp2 = H.insert (Entry expiry1 key) hp1
4900 in ejectLoop hp2 mp out cnt
4901 else return (hp, mp, out, cnt)
4903 assert (Map.null mp) (return ())
4904 return (hp, mp, out, cnt)
4906 -- merge timer events in the stream
4907 stream = Serial.map Just str `Par.parallelFst` repeatM timer
4909 liftIO $ threadDelay (round $ tick * 1000000)
4912-- | Like 'classifySessionsOf' but the session is kept alive if an event is
4913-- received within the session window. The session times out and gets closed
4914-- only if no event is received within the specified session window size.
4916-- If the ejection predicate returns 'True', the session that was idle for
4917-- the longest time is ejected before inserting a new session.
4920-- classifyKeepAliveSessions timeout pred = classifySessionsBy 1 timeout True pred
4925{-# INLINABLE classifyKeepAliveSessions #-}
4926classifyKeepAliveSessions
4927 :: (IsStream t, MonadAsync m, Ord k)
4928 => Double -- ^ session inactive timeout
4929 -> (Int -> m Bool) -- ^ predicate to eject sessions on session count
4930 -> Fold m a (Either b b) -- ^ Fold to be applied to session payload data
4931 -> t m (k, a, AbsTime) -- ^ session key, data, timestamp
4933classifyKeepAliveSessions tmout =
4934 classifySessionsBy 1 tmout True
4936------------------------------------------------------------------------------
4937-- Keyed tumbling windows
4938------------------------------------------------------------------------------
4940-- Tumbling windows is a special case of sliding windows where the window slide
4941-- is the same as the window size. Or it can be a special case of session
4942-- windows where the reset flag is set to False.
4944-- XXX instead of using the early termination flag in the stream, we can use an
4945-- early terminating fold instead.
4948-- | Split the stream into fixed size chunks of specified size. Within each
4949-- such chunk fold the elements in buckets identified by the keys. A particular
4950-- bucket fold can be terminated early if a closing flag is encountered in an
4951-- element for that key.
4954{-# INLINABLE classifyChunksOf #-}
4956 :: (IsStream t, MonadAsync m, Ord k)
4957 => Int -- ^ window size
4958 -> Fold m a b -- ^ Fold to be applied to window events
4959 -> t m (k, a, Bool) -- ^ window key, data, close event
4961classifyChunksOf wsize = classifyChunksBy wsize False
4964-- | Split the stream into fixed size time windows of specified interval in
4965-- seconds. Within each such window, fold the elements in sessions identified
4966-- by the session keys. The fold result is emitted in the output stream if the
4967-- fold returns a 'Left' result or if the time window ends.
4969-- Session @timestamp@ in the input stream is an absolute time from some epoch,
4970-- characterizing the time when the input element was generated. To detect
4971-- session window end, a monotonic event time clock is maintained synced with
4972-- the timestamps with a clock resolution of 1 second.
4974-- If the ejection predicate returns 'True', the session with the longest
4975-- lifetime is ejected before inserting a new session.
4978-- classifySessionsOf interval pred = classifySessionsBy 1 interval False pred
4983-- $ S.classifySessionsOf 3 (const (return False)) (fmap Right FL.toList)
4984-- $ S.map (\(ts,(k,a)) -> (k, a, ts))
4987-- $ (,) <$> S.fromList [1,2,3] <*> S.fromList [1,2,3]
4992{-# INLINABLE classifySessionsOf #-}
4994 :: (IsStream t, MonadAsync m, Ord k)
4995 => Double -- ^ time window size
4996 -> (Int -> m Bool) -- ^ predicate to eject sessions on session count
4997 -> Fold m a (Either b b) -- ^ Fold to be applied to session events
4998 -> t m (k, a, AbsTime) -- ^ session key, data, timestamp
5000classifySessionsOf interval =
5001 classifySessionsBy 1 interval False
5003------------------------------------------------------------------------------
5005------------------------------------------------------------------------------
5007-- | Run a side effect before the stream yields its first element.
5009-- > before action xs = 'nilM' action <> xs
5012{-# INLINE before #-}
5013before :: (IsStream t, Monad m) => m b -> t m a -> t m a
5014before action xs = D.fromStreamD $ D.before action $ D.toStreamD xs
5016-- | Run a side effect at the end of the stream. The side effect won't run if
5017-- the stream is garbage collected before it reached the end.
5019-- > after_ action xs = xs <> 'nilM' action
5021-- This has slightly better performance than 'after'.
5025{-# INLINE after_ #-}
5026after_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
5027after_ action xs = D.fromStreamD $ D.after_ action $ D.toStreamD xs
5029-- | Run a side effect at the end of the stream or if it is garbage collected
5030-- even before reaching the end.
5035after :: (IsStream t, MonadIO m, MonadBaseControl IO m)
5036 => m b -> t m a -> t m a
5037after action xs = D.fromStreamD $ D.after action $ D.toStreamD xs
5039-- | Run a side effect whenever the stream aborts due to an exception.
5042{-# INLINE onException #-}
5043onException :: (IsStream t, MonadCatch m) => m b -> t m a -> t m a
5044onException action xs = D.fromStreamD $ D.onException action $ D.toStreamD xs
5046-- | Run a side effect at the end of the stream or if it aborts due to an
5047-- exception before it could reach the end. The side effect is not run if the
5048-- stream is garbage collected before reaching the end.
5050-- This has slightly better performance than 'finally'.
5054{-# INLINE finally_ #-}
5055finally_ :: (IsStream t, MonadCatch m) => m b -> t m a -> t m a
5056finally_ action xs = D.fromStreamD $ D.finally_ action $ D.toStreamD xs
5058-- | Run a side effect at the end of the stream, or if it aborts due to an
5059-- exception or if it is garbage collected before it could reach the end.
5063{-# INLINE finally #-}
5064finally :: (IsStream t, MonadAsync m, MonadCatch m) => m b -> t m a -> t m a
5065finally action xs = D.fromStreamD $ D.finally action $ D.toStreamD xs
5067-- | Run the first action before the stream starts and remember its output,
5068-- generate a stream using the output, run the second action using the
5069-- remembered value as an argument whenever the stream ends normally or due to
5070-- an exception. The second action won't run if the stream is garbage collected
5071-- before it could reach the end.
5073-- This has slightly better performance than 'bracket'.
5077{-# INLINE bracket_ #-}
5078bracket_ :: (IsStream t, MonadCatch m)
5079 => m b -> (b -> m c) -> (b -> t m a) -> t m a
5080bracket_ bef aft bet = D.fromStreamD $
5081 D.bracket_ bef aft (toStreamD . bet)
5083-- | Run the first action before the stream starts and remember its output,
5084-- generate a stream using the output, run the second action using the
5085-- remembered value as an argument whenever the stream ends normally, due to
5086-- an exception or if it is garbage collected after a partial lazy evaluation.
5090{-# INLINE bracket #-}
5091bracket :: (IsStream t, MonadAsync m, MonadCatch m)
5092 => m b -> (b -> m c) -> (b -> t m a) -> t m a
5093bracket bef aft bet = D.fromStreamD $
5094 D.bracket bef aft (toStreamD . bet)
5096-- | When evaluating a stream if an exception occurs, stream evaluation aborts
5097-- and the specified exception handler is run with the exception as argument.
5100{-# INLINE handle #-}
5101handle :: (IsStream t, MonadCatch m, Exception e)
5102 => (e -> t m a) -> t m a -> t m a
5104 D.fromStreamD $ D.handle (D.toStreamD . handler) $ D.toStreamD xs
5106-- Keep concating either streams as long as rights are generated, stop as soon
5107-- as a left is generated and concat the left stream.
5109-- See also: 'handle'
5115 :: -- (IsStream t, MonadAsync m) =>
5116 (forall x. t m x -> t m x -> t m x)
5117 -> (a -> t m (Either (t m b) b))
5120concatMapEitherWith = undefined
5123------------------------------------------------------------------------------
5124-- Generalize the underlying monad
5125------------------------------------------------------------------------------
5127-- | Transform the inner monad of a stream using a natural transformation.
5132hoist :: (Monad m, Monad n)
5133 => (forall x. m x -> n x) -> SerialT m a -> SerialT n a
5134hoist f xs = fromStreamS $ S.hoist f (toStreamS xs)
5136-- | Generalize the inner monad of the stream from 'Identity' to any monad.
5140{-# INLINE generally #-}
5141generally :: (IsStream t, Monad m) => t Identity a -> t m a
5142generally xs = fromStreamS $ S.hoist (return . runIdentity) (toStreamS xs)
5144------------------------------------------------------------------------------
5145-- Add and remove a monad transformer
5146------------------------------------------------------------------------------
5148-- | Lift the inner monad @m@ of a stream @t m a@ to @tr m@ using the monad
5153{-# INLINE liftInner #-}
5154liftInner :: (Monad m, IsStream t, MonadTrans tr, Monad (tr m))
5155 => t m a -> t (tr m) a
5156liftInner xs = fromStreamD $ D.liftInner (toStreamD xs)
5158------------------------------------------------------------------------------
5159-- Sharing read only state in a stream
5160------------------------------------------------------------------------------
5162-- | Evaluate the inner monad of a stream as 'ReaderT'.
5166{-# INLINE runReaderT #-}
5167runReaderT :: (IsStream t, Monad m) => m s -> t (ReaderT s m) a -> t m a
5168runReaderT s xs = fromStreamD $ D.runReaderT s (toStreamD xs)
5170-- | Run a stream transformation using a given environment.
5172-- See also: 'Serial.map'
5176{-# INLINE usingReaderT #-}
5178 :: (Monad m, IsStream t)
5180 -> (t (ReaderT r m) a -> t (ReaderT r m) a)
5183usingReaderT r f xs = runReaderT r $ f $ liftInner xs
5185------------------------------------------------------------------------------
5186-- Sharing read write state in a stream
5187------------------------------------------------------------------------------
5189-- | Evaluate the inner monad of a stream as 'StateT'.
5191-- This is supported only for 'SerialT' as concurrent state updation may not be
5196{-# INLINE evalStateT #-}
5197evalStateT :: Monad m => m s -> SerialT (StateT s m) a -> SerialT m a
5198evalStateT s xs = fromStreamD $ D.evalStateT s (toStreamD xs)
5200-- | Run a stateful (StateT) stream transformation using a given state.
5202-- This is supported only for 'SerialT' as concurrent state updation may not be
5205-- See also: 'scanl''
5209{-# INLINE usingStateT #-}
5213 -> (SerialT (StateT s m) a -> SerialT (StateT s m) a)
5216usingStateT s f xs = evalStateT s $ f $ liftInner xs
5218-- | Evaluate the inner monad of a stream as 'StateT' and emit the resulting
5219-- state and value pair after each step.
5221-- This is supported only for 'SerialT' as concurrent state updation may not be
5226{-# INLINE runStateT #-}
5227runStateT :: Monad m => m s -> SerialT (StateT s m) a -> SerialT m (s, a)
5228runStateT 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