1{-# OPTIONS_GHC -Wno-orphans #-}
6-- Module : Streamly.Internal.Data.Stream.IsStream
7-- Copyright : (c) 2017 Composewell Technologies
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.
1403-- /Since: 0.8.0 (signature change)/
1404{-# INLINE foldlM' #-}
1405foldlM' :: Monad m => (b -> a -> m b) -> m b -> SerialT m a -> m b
1406foldlM' step begin m = S.foldlM' step begin $ toStreamS m
1408------------------------------------------------------------------------------
1410------------------------------------------------------------------------------
1412-- | Fold a stream using the supplied left fold.
1414-- >>> S.fold FL.sum (S.enumerateFromTo 1 100)
1419fold :: Monad m => Fold m a b -> SerialT m a -> m b
1422------------------------------------------------------------------------------
1424------------------------------------------------------------------------------
1427-- | Drain a stream to a 'Sink'.
1428{-# INLINE runSink #-}
1429runSink :: Monad m => Sink m a -> SerialT m a -> m ()
1430runSink = fold . toFold
1433------------------------------------------------------------------------------
1435------------------------------------------------------------------------------
1437-- | Parse a stream using the supplied 'Parser'.
1441{-# INLINE_NORMAL parseD #-}
1442parseD :: MonadThrow m => PRD.Parser m a b -> SerialT m a -> m b
1443parseD (PRD.Parser step initial extract) = P.parselMx' step initial extract
1445{-# INLINE parseK #-}
1446parseK :: MonadThrow m => PRK.Parser m a b -> SerialT m a -> m b
1449-- | Parse a stream using the supplied 'Parser'.
1453{-# INLINE [3] parse #-}
1454parse :: MonadThrow m => Parser m a b -> SerialT m a -> m b
1455parse = parseD . PRK.fromParserK
1457------------------------------------------------------------------------------
1459------------------------------------------------------------------------------
1462-- > drain = mapM_ (\_ -> return ())
1464-- Run a stream, discarding the results. By default it interprets the stream
1465-- as 'SerialT', to run other types of streams use the type adapting
1466-- combinators for example @drain . 'asyncly'@.
1470drain :: Monad m => SerialT m a -> m ()
1473-- | Run a stream, discarding the results. By default it interprets the stream
1474-- as 'SerialT', to run other types of streams use the type adapting
1475-- combinators for example @runStream . 'asyncly'@.
1478{-# DEPRECATED runStream "Please use \"drain\" instead" #-}
1479{-# INLINE runStream #-}
1480runStream :: Monad m => SerialT m a -> m ()
1484-- > drainN n = drain . take n
1486-- Run maximum up to @n@ iterations of a stream.
1489{-# INLINE drainN #-}
1490drainN :: Monad m => Int -> SerialT m a -> m ()
1491drainN n = drain . take n
1494-- > runN n = runStream . take n
1496-- Run maximum up to @n@ iterations of a stream.
1499{-# DEPRECATED runN "Please use \"drainN\" instead" #-}
1501runN :: Monad m => Int -> SerialT m a -> m ()
1505-- > drainWhile p = drain . takeWhile p
1507-- Run a stream as long as the predicate holds true.
1510{-# INLINE drainWhile #-}
1511drainWhile :: Monad m => (a -> Bool) -> SerialT m a -> m ()
1512drainWhile p = drain . takeWhile p
1515-- > runWhile p = runStream . takeWhile p
1517-- Run a stream as long as the predicate holds true.
1520{-# DEPRECATED runWhile "Please use \"drainWhile\" instead" #-}
1521{-# INLINE runWhile #-}
1522runWhile :: Monad m => (a -> Bool) -> SerialT m a -> m ()
1523runWhile = drainWhile
1525-- | Determine whether the stream is empty.
1529null :: Monad m => SerialT m a -> m Bool
1530null = S.null . toStreamS
1532-- | Extract the first element of the stream, if any.
1538head :: Monad m => SerialT m a -> m (Maybe a)
1539head = S.head . toStreamS
1541-- | Extract the first element of the stream, if any, otherwise use the
1542-- supplied default value. It can help avoid one branch in high performance
1546{-# INLINE headElse #-}
1547headElse :: Monad m => a -> SerialT m a -> m a
1548headElse x = D.headElse x . toStreamD
1551-- > tail = fmap (fmap snd) . uncons
1553-- Extract all but the first element of the stream, if any.
1557tail :: (IsStream t, Monad m) => SerialT m a -> m (Maybe (t m a))
1558tail m = K.tail (K.adapt m)
1560-- | Extract all but the last element of the stream, if any.
1564init :: (IsStream t, Monad m) => SerialT m a -> m (Maybe (t m a))
1565init m = K.init (K.adapt m)
1567-- | Extract the last element of the stream, if any.
1569-- > last xs = xs !! (length xs - 1)
1573last :: Monad m => SerialT m a -> m (Maybe a)
1574last m = S.last $ toStreamS m
1576-- | Determine whether an element is present in the stream.
1580elem :: (Monad m, Eq a) => a -> SerialT m a -> m Bool
1581elem e m = S.elem e (toStreamS m)
1583-- | Determine whether an element is not present in the stream.
1586{-# INLINE notElem #-}
1587notElem :: (Monad m, Eq a) => a -> SerialT m a -> m Bool
1588notElem e m = S.notElem e (toStreamS m)
1590-- | Determine the length of the stream.
1593{-# INLINE length #-}
1594length :: Monad m => SerialT m a -> m Int
1595length = foldl' (\n _ -> n + 1) 0
1597-- | Determine whether all elements of a stream satisfy a predicate.
1601all :: Monad m => (a -> Bool) -> SerialT m a -> m Bool
1602all p m = S.all p (toStreamS m)
1604-- | Determine whether any of the elements of a stream satisfy a predicate.
1608any :: Monad m => (a -> Bool) -> SerialT m a -> m Bool
1609any p m = S.any p (toStreamS m)
1611-- | Determines if all elements of a boolean stream are True.
1615and :: Monad m => SerialT m Bool -> m Bool
1618-- | Determines whether at least one element of a boolean stream is True.
1622or :: Monad m => SerialT m Bool -> m Bool
1625-- | Determine the sum of all elements of a stream of numbers. Returns @0@ when
1626-- the stream is empty. Note that this is not numerically stable for floating
1631sum :: (Monad m, Num a) => SerialT m a -> m a
1634-- | Determine the product of all elements of a stream of numbers. Returns @1@
1635-- when the stream is empty.
1638{-# INLINE product #-}
1639product :: (Monad m, Num a) => SerialT m a -> m a
1640product = foldl' (*) 1
1642-- | Fold a stream of monoid elements by appending them.
1645{-# INLINE mconcat #-}
1646mconcat :: (Monad m, Monoid a) => SerialT m a -> m a
1647mconcat = foldr mappend mempty
1651-- minimum = 'minimumBy' compare
1654-- Determine the minimum element in a stream.
1657{-# INLINE minimum #-}
1658minimum :: (Monad m, Ord a) => SerialT m a -> m (Maybe a)
1659minimum m = S.minimum (toStreamS m)
1661-- | Determine the minimum element in a stream using the supplied comparison
1665{-# INLINE minimumBy #-}
1666minimumBy :: Monad m => (a -> a -> Ordering) -> SerialT m a -> m (Maybe a)
1667minimumBy cmp m = S.minimumBy cmp (toStreamS m)
1671-- maximum = 'maximumBy' compare
1674-- Determine the maximum element in a stream.
1677{-# INLINE maximum #-}
1678maximum :: (Monad m, Ord a) => SerialT m a -> m (Maybe a)
1681-- | Determine the maximum element in a stream using the supplied comparison
1685{-# INLINE maximumBy #-}
1686maximumBy :: Monad m => (a -> a -> Ordering) -> SerialT m a -> m (Maybe a)
1687maximumBy cmp m = S.maximumBy cmp (toStreamS m)
1689-- | Lookup the element at the given index.
1693(!!) :: Monad m => SerialT m a -> Int -> m (Maybe a)
1694m !! i = toStreamS m S.!! i
1696-- | In a stream of (key-value) pairs @(a, b)@, return the value @b@ of the
1697-- first pair where the key equals the given value @a@.
1699-- > lookup = snd <$> find ((==) . fst)
1702{-# INLINE lookup #-}
1703lookup :: (Monad m, Eq a) => a -> SerialT m (a, b) -> m (Maybe b)
1704lookup a m = S.lookup a (toStreamS m)
1706-- | Like 'findM' but with a non-monadic predicate.
1708-- > find p = findM (return . p)
1712find :: Monad m => (a -> Bool) -> SerialT m a -> m (Maybe a)
1713find p m = S.find p (toStreamS m)
1715-- | Returns the first element that satisfies the given predicate.
1719findM :: Monad m => (a -> m Bool) -> SerialT m a -> m (Maybe a)
1720findM p m = S.findM p (toStreamS m)
1722-- | Find all the indices where the element in the stream satisfies the given
1726{-# INLINE findIndices #-}
1727findIndices :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m Int
1728findIndices p m = fromStreamS $ S.findIndices p (toStreamS m)
1730-- | Returns the first index that satisfies the given predicate.
1733{-# INLINE findIndex #-}
1734findIndex :: Monad m => (a -> Bool) -> SerialT m a -> m (Maybe Int)
1735findIndex p = head . findIndices p
1737-- | Find all the indices where the value of the element in the stream is equal
1738-- to the given value.
1741{-# INLINE elemIndices #-}
1742elemIndices :: (IsStream t, Eq a, Monad m) => a -> t m a -> t m Int
1743elemIndices a = findIndices (==a)
1745-- | Returns the first index where a given value is found in the stream.
1747-- > elemIndex a = findIndex (== a)
1750{-# INLINE elemIndex #-}
1751elemIndex :: (Monad m, Eq a) => a -> SerialT m a -> m (Maybe Int)
1752elemIndex a = findIndex (== a)
1754------------------------------------------------------------------------------
1756------------------------------------------------------------------------------
1758-- | Returns 'True' if the first stream is the same as or a prefix of the
1759-- second. A stream is a prefix of itself.
1762-- > S.isPrefixOf (S.fromList "hello") (S.fromList "hello" :: SerialT IO Char)
1767{-# INLINE isPrefixOf #-}
1768isPrefixOf :: (Eq a, IsStream t, Monad m) => t m a -> t m a -> m Bool
1769isPrefixOf m1 m2 = D.isPrefixOf (toStreamD m1) (toStreamD m2)
1771-- Note: isPrefixOf uses the prefix stream only once. In contrast, isSuffixOf
1772-- may use the suffix stream many times. To run in optimal memory we do not
1773-- want to buffer the suffix stream in memory therefore we need an ability to
1774-- clone (or consume it multiple times) the suffix stream without any side
1775-- effects so that multiple potential suffix matches can proceed in parallel
1776-- without buffering the suffix stream. For example, we may create the suffix
1777-- stream from a file handle, however, if we evaluate the stream multiple
1778-- times, once for each match, we will need a different file handle each time
1779-- which may exhaust the file descriptors. Instead, we want to share the same
1780-- underlying file descriptor, use pread on it to generate the stream and clone
1781-- the stream for each match. Therefore the suffix stream should be built in
1782-- such a way that it can be consumed multiple times without any problems.
1784-- XXX Can be implemented with better space/time complexity.
1785-- Space: @O(n)@ worst case where @n@ is the length of the suffix.
1787-- | Returns 'True' if the first stream is a suffix of the second. A stream is
1788-- considered a suffix of itself.
1791-- > S.isSuffixOf (S.fromList "hello") (S.fromList "hello" :: SerialT IO Char)
1795-- Space: @O(n)@, buffers entire input stream and the suffix.
1799-- /Suboptimal/ - Help wanted.
1801{-# INLINE isSuffixOf #-}
1802isSuffixOf :: (Monad m, Eq a) => SerialT m a -> SerialT m a -> m Bool
1803isSuffixOf suffix stream = reverse suffix `isPrefixOf` reverse stream
1805-- | Returns 'True' if the first stream is an infix of the second. A stream is
1806-- considered an infix of itself.
1809-- > S.isInfixOf (S.fromList "hello") (S.fromList "hello" :: SerialT IO Char)
1813-- Space: @O(n)@ worst case where @n@ is the length of the infix.
1817-- /Requires 'Storable' constraint/ - Help wanted.
1819{-# INLINE isInfixOf #-}
1820isInfixOf :: (MonadIO m, Eq a, Enum a, Storable a)
1821 => SerialT m a -> SerialT m a -> m Bool
1822isInfixOf infx stream = do
1823 arr <- fold A.write infx
1824 -- XXX can use breakOnSeq instead (when available)
1825 r <- null $ drop 1 $ splitOnSeq arr FL.drain stream
1828-- | Returns 'True' if all the elements of the first stream occur, in order, in
1829-- the second stream. The elements do not have to occur consecutively. A stream
1830-- is a subsequence of itself.
1833-- > S.isSubsequenceOf (S.fromList "hlo") (S.fromList "hello" :: SerialT IO Char)
1838{-# INLINE isSubsequenceOf #-}
1839isSubsequenceOf :: (Eq a, IsStream t, Monad m) => t m a -> t m a -> m Bool
1840isSubsequenceOf m1 m2 = D.isSubsequenceOf (toStreamD m1) (toStreamD m2)
1842-- | Strip prefix if present and tell whether it was stripped or not. Returns
1843-- 'Nothing' if the stream does not start with the given prefix, stripped
1844-- stream otherwise. Returns @Just nil@ when the prefix is the same as the
1850{-# INLINE stripPrefix #-}
1852 :: (Eq a, IsStream t, Monad m)
1853 => t m a -> t m a -> m (Maybe (t m a))
1854stripPrefix m1 m2 = fmap fromStreamD <$>
1855 D.stripPrefix (toStreamD m1) (toStreamD m2)
1857-- Note: If we want to return a Maybe value to know whether the
1858-- suffix/infix was present or not along with the stripped stream then
1859-- we need to buffer the whole input stream.
1861-- | Drops the given suffix from a stream. Returns 'Nothing' if the stream does
1862-- not end with the given suffix. Returns @Just nil@ when the suffix is the
1863-- same as the stream.
1865-- It may be more efficient to convert the stream to an Array and use
1866-- stripSuffix on that especially if the elements have a Storable or Prim
1869-- Space: @O(n)@, buffers the entire input stream as well as the suffix
1872{-# INLINE stripSuffix #-}
1875 => SerialT m a -> SerialT m a -> m (Maybe (SerialT m a))
1876stripSuffix m1 m2 = fmap reverse <$> stripPrefix (reverse m1) (reverse m2)
1878-- | Drop prefix from the input stream if present.
1882-- /Unimplemented/ - Help wanted.
1883{-# INLINE dropPrefix #-}
1885 -- (Eq a, IsStream t, Monad m) =>
1886 t m a -> t m a -> t m a
1887dropPrefix = error "Not implemented yet!"
1889-- | Drop all matching infix from the input stream if present. Infix stream
1890-- may be consumed multiple times.
1892-- Space: @O(n)@ where n is the length of the infix.
1894-- /Unimplemented/ - Help wanted.
1895{-# INLINE dropInfix #-}
1897 -- (Eq a, IsStream t, Monad m) =>
1898 t m a -> t m a -> t m a
1899dropInfix = error "Not implemented yet!"
1901-- | Drop suffix from the input stream if present. Suffix stream may be
1902-- consumed multiple times.
1904-- Space: @O(n)@ where n is the length of the suffix.
1906-- /Unimplemented/ - Help wanted.
1907{-# INLINE dropSuffix #-}
1909 -- (Eq a, IsStream t, Monad m) =>
1910 t m a -> t m a -> t m a
1911dropSuffix = error "Not implemented yet!"
1913------------------------------------------------------------------------------
1915------------------------------------------------------------------------------
1917-- XXX this can utilize parallel mapping if we implement it as drain . mapM
1919-- > mapM_ = drain . mapM
1921-- Apply a monadic action to each element of the stream and discard the output
1922-- of the action. This is not really a pure transformation operation but a
1923-- transformation followed by fold.
1927mapM_ :: Monad m => (a -> m b) -> SerialT m a -> m ()
1928mapM_ f m = S.mapM_ f $ toStreamS m
1930------------------------------------------------------------------------------
1932------------------------------------------------------------------------------
1936-- toList = S.foldr (:) []
1939-- Convert a stream into a list in the underlying monad. The list can be
1940-- consumed lazily in a lazy monad (e.g. 'Identity'). In a strict monad (e.g.
1941-- IO) the whole list is generated and buffered before it can be consumed.
1943-- /Warning!/ working on large lists accumulated as buffers in memory could be
1944-- very inefficient, consider using "Streamly.Array" instead.
1947{-# INLINE toList #-}
1948toList :: Monad m => SerialT m a -> m [a]
1953-- toListRev = S.foldl' (flip (:)) []
1956-- Convert a stream into a list in reverse order in the underlying monad.
1958-- /Warning!/ working on large lists accumulated as buffers in memory could be
1959-- very inefficient, consider using "Streamly.Array" instead.
1962{-# INLINE toListRev #-}
1963toListRev :: Monad m => SerialT m a -> m [a]
1964toListRev = D.toListRev . toStreamD
1968-- toHandle h = S.mapM_ $ hPutStrLn h
1971-- Write a stream of Strings to an IO Handle.
1974{-# DEPRECATED toHandle
1975 "Please use Streamly.FileSystem.Handle module (see the changelog)" #-}
1976toHandle :: MonadIO m => IO.Handle -> SerialT m String -> m ()
1980 let stop = return ()
1981 single a = liftIO (IO.hPutStrLn h a)
1982 yieldk a r = liftIO (IO.hPutStrLn h a) >> go r
1983 in K.foldStream defState yieldk single stop m1
1985-- XXX rename these to write/writeRev to make the naming consistent with folds
1988-- | A fold that buffers its input to a pure stream.
1990-- /Warning!/ working on large streams accumulated as buffers in memory could
1991-- be very inefficient, consider using "Streamly.Data.Array" instead.
1994{-# INLINE toStream #-}
1995toStream :: Monad m => Fold m a (SerialT Identity a)
1996toStream = Fold (\f x -> return $ f . (x `K.cons`))
1998 (return . ($ K.nil))
2000-- This is more efficient than 'toStream'. toStream is exactly the same as
2001-- reversing the stream after toStreamRev.
2003-- | Buffers the input stream to a pure stream in the reverse order of the
2006-- /Warning!/ working on large streams accumulated as buffers in memory could
2007-- be very inefficient, consider using "Streamly.Data.Array" instead.
2011-- xn : ... : x2 : x1 : []
2012{-# INLINABLE toStreamRev #-}
2013toStreamRev :: Monad m => Fold m a (SerialT Identity a)
2014toStreamRev = Fold (\xs x -> return $ x `K.cons` xs) (return K.nil) return
2016-- | Convert a stream to a pure stream.
2019-- toPure = foldr cons nil
2024{-# INLINE toPure #-}
2025toPure :: Monad m => SerialT m a -> m (SerialT Identity a)
2026toPure = foldr K.cons K.nil
2028-- | Convert a stream to a pure stream in reverse order.
2031-- toPureRev = foldl' (flip cons) nil
2036{-# INLINE toPureRev #-}
2037toPureRev :: Monad m => SerialT m a -> m (SerialT Identity a)
2038toPureRev = foldl' (flip K.cons) K.nil
2040------------------------------------------------------------------------------
2041-- Concurrent Application
2042------------------------------------------------------------------------------
2050-- | Parallel transform application operator; applies a stream transformation
2051-- function @t m a -> t m b@ to a stream @t m a@ concurrently; the input stream
2052-- is evaluated asynchronously in an independent thread yielding elements to a
2053-- buffer and the transformation function runs in another thread consuming the
2054-- input from the buffer. '|$' is just like regular function application
2055-- operator '$' except that it is concurrent.
2057-- If you read the signature as @(t m a -> t m b) -> (t m a -> t m b)@ you can
2058-- look at it as a transformation that converts a transform function to a
2059-- buffered concurrent transform function.
2061-- The following code prints a value every second even though each stage adds a
2067-- S.mapM (\\x -> threadDelay 1000000 >> print x)
2068-- |$ S.repeatM (threadDelay 1000000 >> return 1)
2073-- /Since: 0.3.0 ("Streamly")/
2077(|$) :: (IsStream t, MonadAsync m) => (t m a -> t m b) -> (t m a -> t m b)
2078-- (|$) f = f . Async.mkAsync
2079(|$) f = f . D.mkParallel
2085{-# INLINE applyAsync #-}
2086applyAsync :: (IsStream t, MonadAsync m)
2087 => (t m a -> t m b) -> (t m a -> t m b)
2090-- | Parallel reverse function application operator for streams; just like the
2091-- regular reverse function application operator '&' except that it is
2096-- S.repeatM (threadDelay 1000000 >> return 1)
2097-- |& S.mapM (\\x -> threadDelay 1000000 >> print x)
2102-- /Since: 0.3.0 ("Streamly")/
2106(|&) :: (IsStream t, MonadAsync m) => t m a -> (t m a -> t m b) -> t m b
2109-- | Parallel fold application operator; applies a fold function @t m a -> m b@
2110-- to a stream @t m a@ concurrently; The the input stream is evaluated
2111-- asynchronously in an independent thread yielding elements to a buffer and
2112-- the folding action runs in another thread consuming the input from the
2115-- If you read the signature as @(t m a -> m b) -> (t m a -> m b)@ you can look
2116-- at it as a transformation that converts a fold function to a buffered
2117-- concurrent fold function.
2119-- The @.@ at the end of the operator is a mnemonic for termination of the
2123-- S.foldlM' (\\_ a -> threadDelay 1000000 >> print a) ()
2124-- |$. S.repeatM (threadDelay 1000000 >> return 1)
2129-- /Since: 0.3.0 ("Streamly")/
2133(|$.) :: (IsStream t, MonadAsync m) => (t m a -> m b) -> (t m a -> m b)
2134-- (|$.) f = f . Async.mkAsync
2135(|$.) f = f . D.mkParallel
2141{-# INLINE foldAsync #-}
2142foldAsync :: (IsStream t, MonadAsync m) => (t m a -> m b) -> (t m a -> m b)
2145-- | Parallel reverse function application operator for applying a run or fold
2146-- functions to a stream. Just like '|$.' except that the operands are reversed.
2149-- S.repeatM (threadDelay 1000000 >> return 1)
2150-- |&. S.foldlM' (\\_ a -> threadDelay 1000000 >> print a) ()
2155-- /Since: 0.3.0 ("Streamly")/
2159(|&.) :: (IsStream t, MonadAsync m) => t m a -> (t m a -> m b) -> m b
2162------------------------------------------------------------------------------
2163-- General Transformation
2164------------------------------------------------------------------------------
2166-- | Use a 'Pipe' to transform a stream.
2170{-# INLINE transform #-}
2171transform :: (IsStream t, Monad m) => Pipe m a b -> t m a -> t m b
2172transform pipe xs = fromStreamD $ D.transform pipe (toStreamD xs)
2174------------------------------------------------------------------------------
2175-- Transformation by Folding (Scans)
2176------------------------------------------------------------------------------
2178-- XXX It may be useful to have a version of scan where we can keep the
2179-- accumulator independent of the value emitted. So that we do not necessarily
2180-- have to keep a value in the accumulator which we are not using. We can pass
2181-- an extraction function that will take the accumulator and the current value
2182-- of the element and emit the next value in the stream. That will also make it
2183-- possible to modify the accumulator after using it. In fact, the step function
2184-- can return new accumulator and the value to be emitted. The signature would
2185-- be more like mapAccumL. Or we can change the signature of scanx to
2188-- | Strict left scan with an extraction function. Like 'scanl'', but applies a
2189-- user supplied extraction function (the third argument) at each step. This is
2190-- designed to work with the @foldl@ library. The suffix @x@ is a mnemonic for
2195-- /Since: 0.7.0 (Monad m constraint)/
2196{-# DEPRECATED scanx "Please use scanl followed by map instead." #-}
2198scanx :: (IsStream t, Monad m) => (x -> a -> x) -> x -> (x -> b) -> t m a -> t m b
2201-- XXX this needs to be concurrent
2202-- XXX because of the use of D.cons for appending, scanlM' has quadratic
2203-- complexity when iterated over a stream. We should use StreamK style scanlM'
2204-- for linear performance on iteration.
2206-- | Like 'scanl'' but with a monadic step function and a monadic seed.
2210-- /Since: 0.8.0 (signature change)/
2211{-# INLINE scanlM' #-}
2212scanlM' :: (IsStream t, Monad m) => (b -> a -> m b) -> m b -> t m a -> t m b
2213scanlM' step begin m = fromStreamD $ D.scanlM' step begin $ toStreamD m
2215-- | @scanlMAfter' accumulate initial done stream@ is like 'scanlM'' except
2216-- that it provides an additional @done@ function to be applied on the
2217-- accumulator when the stream stops. The result of @done@ is also emitted in
2220-- This function can be used to allocate a resource in the beginning of the
2221-- scan and release it when the stream ends or to flush the internal state of
2222-- the scan at the end.
2226{-# INLINE scanlMAfter' #-}
2227scanlMAfter' :: (IsStream t, Monad m)
2228 => (b -> a -> m b) -> m b -> (b -> m b) -> t m a -> t m b
2229scanlMAfter' step initial done stream =
2230 fromStreamD $ D.scanlMAfter' step initial done $ toStreamD stream
2232-- XXX because of the use of D.cons for appending, scanl' has quadratic
2233-- complexity when iterated over a stream. We should use StreamK style scanlM'
2234-- for linear performance on iteration.
2236-- | Strict left scan. Like 'map', 'scanl'' too is a one to one transformation,
2237-- however it adds an extra element.
2240-- > S.toList $ S.scanl' (+) 0 $ fromList [1,2,3,4]
2245-- > S.toList $ S.scanl' (flip (:)) [] $ S.fromList [1,2,3,4]
2246-- [[],[1],[2,1],[3,2,1],[4,3,2,1]]
2249-- The output of 'scanl'' is the initial value of the accumulator followed by
2250-- all the intermediate steps and the final result of 'foldl''.
2252-- By streaming the accumulated state after each fold step, we can share the
2253-- state across multiple stages of stream composition. Each stage can modify or
2254-- extend the state, do some processing with it and emit it for the next stage,
2255-- thus modularizing the stream processing. This can be useful in
2256-- stateful or event-driven programming.
2258-- Consider the following monolithic example, computing the sum and the product
2259-- of the elements in a stream in one go using a @foldl'@:
2262-- > S.foldl' (\\(s, p) x -> (s + x, p * x)) (0,1) $ S.fromList \[1,2,3,4]
2266-- Using @scanl'@ we can make it modular by computing the sum in the first
2267-- stage and passing it down to the next stage for computing the product:
2270-- > S.foldl' (\\(_, p) (s, x) -> (s, p * x)) (0,1)
2271-- $ S.scanl' (\\(s, _) x -> (s + x, x)) (0,1)
2272-- $ S.fromList \[1,2,3,4]
2276-- IMPORTANT: 'scanl'' evaluates the accumulator to WHNF. To avoid building
2277-- lazy expressions inside the accumulator, it is recommended that a strict
2278-- data structure is used for accumulator.
2280-- See also: 'usingStateT'
2283{-# INLINE scanl' #-}
2284scanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
2285scanl' step z m = fromStreamS $ S.scanl' step z $ toStreamS m
2287-- | Like 'scanl'' but does not stream the initial value of the accumulator.
2289-- > postscanl' f z xs = S.drop 1 $ S.scanl' f z xs
2292{-# INLINE postscanl' #-}
2293postscanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
2294postscanl' step z m = fromStreamD $ D.postscanl' step z $ toStreamD m
2296-- XXX this needs to be concurrent
2297-- | Like 'postscanl'' but with a monadic step function and a monadic seed.
2301-- /Since: 0.8.0 (signature change)/
2302{-# INLINE postscanlM' #-}
2303postscanlM' :: (IsStream t, Monad m) => (b -> a -> m b) -> m b -> t m a -> t m b
2304postscanlM' step z m = fromStreamD $ D.postscanlM' step z $ toStreamD m
2306-- XXX prescanl does not sound very useful, enable only if there is a
2307-- compelling use case.
2309-- | Like scanl' but does not stream the final value of the accumulator.
2312{-# INLINE prescanl' #-}
2313prescanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
2314prescanl' step z m = fromStreamD $ D.prescanl' step z $ toStreamD m
2316-- XXX this needs to be concurrent
2317-- | Like prescanl' but with a monadic step function and a monadic seed.
2320{-# INLINE prescanlM' #-}
2321prescanlM' :: (IsStream t, Monad m) => (b -> a -> m b) -> m b -> t m a -> t m b
2322prescanlM' step z m = fromStreamD $ D.prescanlM' step z $ toStreamD m
2324-- XXX this needs to be concurrent
2325-- | Like 'scanl1'' but with a monadic step function.
2328{-# INLINE scanl1M' #-}
2329scanl1M' :: (IsStream t, Monad m) => (a -> a -> m a) -> t m a -> t m a
2330scanl1M' step m = fromStreamD $ D.scanl1M' step $ toStreamD m
2332-- | Like 'scanl'' but for a non-empty stream. The first element of the stream
2333-- is used as the initial value of the accumulator. Does nothing if the stream
2337-- > S.toList $ S.scanl1 (+) $ fromList [1,2,3,4]
2342{-# INLINE scanl1' #-}
2343scanl1' :: (IsStream t, Monad m) => (a -> a -> a) -> t m a -> t m a
2344scanl1' step m = fromStreamD $ D.scanl1' step $ toStreamD m
2346------------------------------------------------------------------------------
2347-- Scanning with a Fold
2348------------------------------------------------------------------------------
2350-- | Scan a stream using the given monadic fold.
2354scan :: (IsStream t, Monad m) => Fold m a b -> t m a -> t m b
2355scan (Fold step begin done) = P.scanlMx' step begin done
2357-- | Postscan a stream using the given monadic fold.
2360{-# INLINE postscan #-}
2361postscan :: (IsStream t, Monad m) => Fold m a b -> t m a -> t m b
2362postscan (Fold step begin done) = P.postscanlMx' step begin done
2364------------------------------------------------------------------------------
2365-- Stateful Transformations
2366------------------------------------------------------------------------------
2368-- XXX this is not a one-to-one map so calling it map may not be right.
2369-- We can perhaps call it zipWithTail or rollWith.
2371-- | Apply a function on every two successive elements of a stream. If the
2372-- stream consists of a single element the output is an empty stream.
2374-- This is the stream equivalent of the list idiom @zipWith f xs (tail xs)@.
2378{-# INLINE rollingMap #-}
2379rollingMap :: (IsStream t, Monad m) => (a -> a -> b) -> t m a -> t m b
2380rollingMap f m = fromStreamD $ D.rollingMap f $ toStreamD m
2382-- | Like 'rollingMap' but with an effectful map function.
2386{-# INLINE rollingMapM #-}
2387rollingMapM :: (IsStream t, Monad m) => (a -> a -> m b) -> t m a -> t m b
2388rollingMapM f m = fromStreamD $ D.rollingMapM f $ toStreamD m
2390------------------------------------------------------------------------------
2391-- Transformation by Filtering
2392------------------------------------------------------------------------------
2394-- | Include only those elements that pass a predicate.
2397{-# INLINE filter #-}
2398#if __GLASGOW_HASKELL__ != 802
2399-- GHC 8.2.2 crashes with this code, when used with "stack"
2400filter :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m a
2401filter p m = fromStreamS $ S.filter p $ toStreamS m
2403filter :: IsStream t => (a -> Bool) -> t m a -> t m a
2407-- | Same as 'filter' but with a monadic predicate.
2410{-# INLINE filterM #-}
2411filterM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
2412filterM p m = fromStreamD $ D.filterM p $ toStreamD m
2414-- | Drop repeated elements that are adjacent to each other.
2418uniq :: (Eq a, IsStream t, Monad m) => t m a -> t m a
2419uniq = fromStreamD . D.uniq . toStreamD
2421-- | Ensures that all the elements of the stream are identical and then returns
2422-- that unique element.
2426the :: (Eq a, Monad m) => SerialT m a -> m (Maybe a)
2427the m = S.the (toStreamS m)
2429-- | Take first 'n' elements from the stream and discard the rest.
2433take :: (IsStream t, Monad m) => Int -> t m a -> t m a
2434take n m = fromStreamS $ S.take n $ toStreamS
2435 (maxYields (Just (fromIntegral n)) m)
2437-- | End the stream as soon as the predicate fails on an element.
2440{-# INLINE takeWhile #-}
2441takeWhile :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m a
2442takeWhile p m = fromStreamS $ S.takeWhile p $ toStreamS m
2444-- | Same as 'takeWhile' but with a monadic predicate.
2447{-# INLINE takeWhileM #-}
2448takeWhileM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
2449takeWhileM p m = fromStreamD $ D.takeWhileM p $ toStreamD m
2451-- | @takeByTime duration@ yields stream elements upto specified time
2452-- @duration@. The duration starts when the stream is evaluated for the first
2453-- time, before the first element is yielded. The time duration is checked
2454-- before generating each element, if the duration has expired the stream
2457-- The total time taken in executing the stream is guaranteed to be /at least/
2458-- @duration@, however, because the duration is checked before generating an
2459-- element, the upper bound is indeterminate and depends on the time taken in
2460-- generating and processing the last element.
2462-- No element is yielded if the duration is zero. At least one element is
2463-- yielded if the duration is non-zero.
2467{-# INLINE takeByTime #-}
2468takeByTime ::(MonadIO m, IsStream t, TimeUnit64 d) => d -> t m a -> t m a
2469takeByTime d = fromStreamD . D.takeByTime d . toStreamD
2471-- | Discard first 'n' elements from the stream and take the rest.
2475drop :: (IsStream t, Monad m) => Int -> t m a -> t m a
2476drop n m = fromStreamS $ S.drop n $ toStreamS m
2478-- | Drop elements in the stream as long as the predicate succeeds and then
2479-- take the rest of the stream.
2482{-# INLINE dropWhile #-}
2483dropWhile :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m a
2484dropWhile p m = fromStreamS $ S.dropWhile p $ toStreamS m
2486-- | Same as 'dropWhile' but with a monadic predicate.
2489{-# INLINE dropWhileM #-}
2490dropWhileM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
2491dropWhileM p m = fromStreamD $ D.dropWhileM p $ toStreamD m
2493-- | @dropByTime duration@ drops stream elements until specified @duration@ has
2494-- passed. The duration begins when the stream is evaluated for the first
2495-- time. The time duration is checked /after/ generating a stream element, the
2496-- element is yielded if the duration has expired otherwise it is dropped.
2498-- The time elapsed before starting to generate the first element is /at most/
2499-- @duration@, however, because the duration expiry is checked after the
2500-- element is generated, the lower bound is indeterminate and depends on the
2501-- time taken in generating an element.
2503-- All elements are yielded if the duration is zero.
2507{-# INLINE dropByTime #-}
2508dropByTime ::(MonadIO m, IsStream t, TimeUnit64 d) => d -> t m a -> t m a
2509dropByTime d = fromStreamD . D.dropByTime d . toStreamD
2511------------------------------------------------------------------------------
2512-- Transformation by Mapping
2513------------------------------------------------------------------------------
2517-- mapM f = sequence . map f
2520-- Apply a monadic function to each element of the stream and replace it with
2521-- the output of the resulting action.
2524-- > drain $ S.mapM putStr $ S.fromList ["a", "b", "c"]
2527-- drain $ S.replicateM 10 (return 1)
2528-- & (serially . S.mapM (\\x -> threadDelay 1000000 >> print x))
2530-- drain $ S.replicateM 10 (return 1)
2531-- & (asyncly . S.mapM (\\x -> threadDelay 1000000 >> print x))
2534-- /Concurrent (do not use with 'parallely' on infinite streams)/
2537{-# INLINE_EARLY mapM #-}
2538mapM :: (IsStream t, MonadAsync m) => (a -> m b) -> t m a -> t m b
2541{-# RULES "mapM serial" mapM = mapMSerial #-}
2542{-# INLINE mapMSerial #-}
2543mapMSerial :: Monad m => (a -> m b) -> SerialT m a -> SerialT m b
2544mapMSerial = Serial.mapM
2548-- sequence = mapM id
2551-- Replace the elements of a stream of monadic actions with the outputs of
2555-- > drain $ S.sequence $ S.fromList [putStr "a", putStr "b", putStrLn "c"]
2558-- drain $ S.replicateM 10 (return $ threadDelay 1000000 >> print 1)
2559-- & (serially . S.sequence)
2561-- drain $ S.replicateM 10 (return $ threadDelay 1000000 >> print 1)
2562-- & (asyncly . S.sequence)
2565-- /Concurrent (do not use with 'parallely' on infinite streams)/
2568{-# INLINE sequence #-}
2569sequence :: (IsStream t, MonadAsync m) => t m (m a) -> t m a
2570sequence m = fromStreamS $ S.sequence (toStreamS m)
2574-- The stateful step function can be simplified to @(s -> a -> m b)@ to provide
2575-- a read-only environment. However, that would just be 'mapM'.
2577-- The initial action could be @m (s, Maybe b)@, and we can also add a final
2578-- action @s -> m (Maybe b)@. This can be used to get pre/post scan like
2579-- functionality and also to flush the state in the end like scanlMAfter'.
2580-- We can also use it along with a fusible version of bracket to get
2581-- scanlMAfter' like functionality. See issue #677.
2583-- This can be further generalized to a type similar to Fold/Parser, giving it
2584-- filtering and parsing capability as well (this is in fact equivalent to
2587-- smapM :: (s -> a -> m (Step s b)) -> m s -> t m a -> t m b
2590-- | A stateful 'mapM', equivalent to a left scan, more like mapAccumL.
2591-- Hopefully, this is a better alternative to @scan@. Separation of state from
2592-- the output makes it easier to think in terms of a shared state, and also
2593-- makes it easier to keep the state fully strict and the output lazy.
2595-- See also: 'scanlM''
2600smapM :: (IsStream t, Monad m) =>
2601 (s -> a -> m (s, b))
2605smapM step initial stream =
2606 -- XXX implement this directly instead of using scanlM'
2607 -- Once we have postscanlM' with monadic initial we can use this code
2608 -- let r = postscanlM'
2609 -- (\(s, _) a -> step s a)
2610 -- (fmap (,undefined) initial)
2613 (\(s, _) a -> step s a)
2614 (fmap (,undefined) initial)
2618------------------------------------------------------------------------------
2620------------------------------------------------------------------------------
2622-- | Map a 'Maybe' returning function to a stream, filter out the 'Nothing'
2623-- elements, and return a stream of values extracted from 'Just'.
2628-- mapMaybe f = S.map 'fromJust' . S.filter 'isJust' . S.map f
2632{-# INLINE mapMaybe #-}
2633mapMaybe :: (IsStream t, Monad m) => (a -> Maybe b) -> t m a -> t m b
2634mapMaybe f m = fromStreamS $ S.mapMaybe f $ toStreamS m
2636-- | Like 'mapMaybe' but maps a monadic function.
2641-- mapMaybeM f = S.map 'fromJust' . S.filter 'isJust' . S.mapM f
2644-- /Concurrent (do not use with 'parallely' on infinite streams)/
2647{-# INLINE_EARLY mapMaybeM #-}
2648mapMaybeM :: (IsStream t, MonadAsync m, Functor (t m))
2649 => (a -> m (Maybe b)) -> t m a -> t m b
2650mapMaybeM f = fmap fromJust . filter isJust . K.mapM f
2652{-# RULES "mapMaybeM serial" mapMaybeM = mapMaybeMSerial #-}
2653{-# INLINE mapMaybeMSerial #-}
2654mapMaybeMSerial :: Monad m => (a -> m (Maybe b)) -> SerialT m a -> SerialT m b
2655mapMaybeMSerial f m = fromStreamD $ D.mapMaybeM f $ toStreamD m
2657-- | In a stream of 'Maybe's, discard 'Nothing's and unwrap 'Just's.
2661catMaybes :: (IsStream t, Monad m, Functor (t m)) => t m (Maybe a) -> t m a
2662catMaybes = fmap fromJust . filter isJust
2664------------------------------------------------------------------------------
2665-- Transformation by Reordering
2666------------------------------------------------------------------------------
2668-- XXX Use a compact region list to temporarily store the list, in both reverse
2669-- as well as in reverse'.
2671-- /Note:/ 'reverse'' is much faster than this, use that when performance
2674-- > reverse = S.foldlT (flip S.cons) S.nil
2676-- | Returns the elements of the stream in reverse order. The stream must be
2677-- finite. Note that this necessarily buffers the entire stream in memory.
2679-- /Since 0.7.0 (Monad m constraint)/
2682{-# INLINE reverse #-}
2683reverse :: (IsStream t, Monad m) => t m a -> t m a
2684reverse s = fromStreamS $ S.reverse $ toStreamS s
2686-- | Like 'reverse' but several times faster, requires a 'Storable' instance.
2689{-# INLINE reverse' #-}
2690reverse' :: (IsStream t, MonadIO m, Storable a) => t m a -> t m a
2691reverse' s = fromStreamD $ D.reverse' $ toStreamD s
2693------------------------------------------------------------------------------
2694-- Transformation by Inserting
2695------------------------------------------------------------------------------
2697-- intersperseM = intersperseBySpan 1
2699-- | Insert an effect and its output before consuming an element of a stream
2700-- except the first one.
2703-- >>> S.toList $ S.trace putChar $ S.intersperseM (putChar '.' >> return ',') $ S.fromList "hello"
2704-- > h.,e.,l.,l.,o"h,e,l,l,o"
2708{-# INLINE intersperseM #-}
2709intersperseM :: (IsStream t, MonadAsync m) => m a -> t m a -> t m a
2710intersperseM m = fromStreamS . S.intersperseM m . toStreamS
2712-- | Insert a side effect before consuming an element of a stream except the
2716-- >>> S.drain $ S.trace putChar $ S.intersperseM_ (putChar '.') $ S.fromList "hello"
2721{-# INLINE intersperseM_ #-}
2722intersperseM_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
2723intersperseM_ m = fromStreamD . D.intersperseM_ m . toStreamD
2725-- | Insert a pure value between successive elements of a stream.
2728-- > S.toList $ S.intersperse ',' $ S.fromList "hello"
2733{-# INLINE intersperse #-}
2734intersperse :: (IsStream t, MonadAsync m) => a -> t m a -> t m a
2735intersperse a = fromStreamS . S.intersperse a . toStreamS
2737-- | Insert an effect and its output after consuming an element of a stream.
2740-- >>> S.toList $ S.trace putChar $ S.intersperseSuffix (putChar '.' >> return ',') $ S.fromList "hello"
2741-- > h.,e.,l.,l.,o.,"h,e,l,l,o,"
2745{-# INLINE intersperseSuffix #-}
2746intersperseSuffix :: (IsStream t, MonadAsync m) => m a -> t m a -> t m a
2747intersperseSuffix m = fromStreamD . D.intersperseSuffix m . toStreamD
2749-- | Insert a side effect after consuming an element of a stream.
2752-- > S.mapM_ putChar $ S.intersperseSuffix_ (threadDelay 1000000) $ S.fromList "hello"
2757{-# INLINE intersperseSuffix_ #-}
2758intersperseSuffix_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
2759intersperseSuffix_ m = fromStreamD . D.intersperseSuffix_ m . toStreamD
2761-- | Insert a side effect before consuming an element of a stream.
2764-- >>> S.toList $ S.trace putChar $ S.interspersePrefix_ (putChar '.' >> return ',') $ S.fromList "hello"
2765-- > .h.e.l.l.o"hello"
2768-- See also: 'trace_'
2774{-# INLINE interspersePrefix_ #-}
2775interspersePrefix_ :: (IsStream t, MonadAsync m) => m b -> t m a -> t m a
2776interspersePrefix_ m = mapM (\x -> void m >> return x)
2778-- Note: delay must be serial.
2780-- | Introduce a delay of specified seconds before consuming an element of the
2781-- stream except the first one.
2784-- >>> S.mapM_ print $ S.timestamped $ S.delay 1 $ S.enumerateFromTo 1 3
2785-- > (AbsTime (TimeSpec {sec = 2502706, nsec = 751137000}),1)
2786-- > (AbsTime (TimeSpec {sec = 2502707, nsec = 743535000}),2)
2787-- > (AbsTime (TimeSpec {sec = 2502708, nsec = 749758000}),3)
2793delay :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
2794delay n = intersperseM_ $ liftIO $ threadDelay $ round $ n * 1000000
2796-- Note: delay must be serial.
2798-- | Introduce a delay of specified seconds after consuming an element of a
2802-- >>> S.mapM_ print $ S.timestamped $ S.delayPost 1 $ S.enumerateFromTo 1 3
2803-- > (AbsTime (TimeSpec {sec = 2502826, nsec = 119030000}),1)
2804-- > (AbsTime (TimeSpec {sec = 2502827, nsec = 111393000}),2)
2805-- > (AbsTime (TimeSpec {sec = 2502828, nsec = 112221000}),3)
2810{-# INLINE delayPost #-}
2811delayPost :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
2812delayPost n = intersperseSuffix_ $ liftIO $ threadDelay $ round $ n * 1000000
2814-- Note: delay must be serial, that's why 'trace_' is used.
2816-- | Introduce a delay of specified seconds before consuming an element of a
2820-- >>> S.mapM_ print $ S.timestamped $ S.delayPre 1 $ S.enumerateFromTo 1 3
2821-- > (AbsTime (TimeSpec {sec = 2502207, nsec = 533177000}),1)
2822-- > (AbsTime (TimeSpec {sec = 2502208, nsec = 530859000}),2)
2823-- > (AbsTime (TimeSpec {sec = 2502209, nsec = 531619000}),3)
2828{-# INLINE delayPre #-}
2829delayPre :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
2830delayPre n = trace_ $ liftIO $ threadDelay $ round $ n * 1000000
2832-- | Like 'intersperseSuffix' but intersperses an effectful action into the
2833-- input stream after every @n@ elements and after the last element.
2836-- > S.toList $ S.intersperseSuffixBySpan 2 (return ',') $ S.fromList "hello"
2842{-# INLINE intersperseSuffixBySpan #-}
2843intersperseSuffixBySpan :: (IsStream t, MonadAsync m)
2844 => Int -> m a -> t m a -> t m a
2845intersperseSuffixBySpan n eff =
2846 fromStreamD . D.intersperseSuffixBySpan n eff . toStreamD
2849-- | Intersperse a monadic action into the input stream after every @n@
2853-- > S.toList $ S.intersperseBySpan 2 (return ',') $ S.fromList "hello"
2858{-# INLINE intersperseBySpan #-}
2859intersperseBySpan :: IsStream t => Int -> m a -> t m a -> t m a
2860intersperseBySpan _n _f _xs = undefined
2863-- | Intersperse a monadic action into the input stream after every @n@
2867-- > S.drain $ S.interjectSuffix 1 (putChar ',') $ S.mapM (\\x -> threadDelay 1000000 >> putChar x) $ S.fromList "hello"
2872{-# INLINE interjectSuffix #-}
2874 :: (IsStream t, MonadAsync m)
2875 => Double -> m a -> t m a -> t m a
2876interjectSuffix n f xs = xs `Par.parallelFst` repeatM timed
2877 where timed = liftIO (threadDelay (round $ n * 1000000)) >> f
2879-- | @insertBy cmp elem stream@ inserts @elem@ before the first element in
2880-- @stream@ that is less than @elem@ when compared using @cmp@.
2883-- insertBy cmp x = 'mergeBy' cmp ('yield' x)
2887-- > S.toList $ S.insertBy compare 2 $ S.fromList [1,3,5]
2892{-# INLINE insertBy #-}
2894 (IsStream t, Monad m) => (a -> a -> Ordering) -> a -> t m a -> t m a
2895insertBy cmp x m = fromStreamS $ S.insertBy cmp x (toStreamS m)
2897------------------------------------------------------------------------------
2899------------------------------------------------------------------------------
2901-- | Deletes the first occurrence of the element in the stream that satisfies
2902-- the given equality predicate.
2905-- > S.toList $ S.deleteBy (==) 3 $ S.fromList [1,3,3,5]
2910{-# INLINE deleteBy #-}
2911deleteBy :: (IsStream t, Monad m) => (a -> a -> Bool) -> a -> t m a -> t m a
2912deleteBy cmp x m = fromStreamS $ S.deleteBy cmp x (toStreamS m)
2914------------------------------------------------------------------------------
2916------------------------------------------------------------------------------
2919-- > indexed = S.postscanl' (\(i, _) x -> (i + 1, x)) (-1,undefined)
2920-- > indexed = S.zipWith (,) (S.enumerateFrom 0)
2922-- Pair each element in a stream with its index, starting from index 0.
2925-- > S.toList $ S.indexed $ S.fromList "hello"
2926-- [(0,'h'),(1,'e'),(2,'l'),(3,'l'),(4,'o')]
2930{-# INLINE indexed #-}
2931indexed :: (IsStream t, Monad m) => t m a -> t m (Int, a)
2932indexed = fromStreamD . D.indexed . toStreamD
2935-- > indexedR n = S.postscanl' (\(i, _) x -> (i - 1, x)) (n + 1,undefined)
2936-- > indexedR n = S.zipWith (,) (S.enumerateFromThen n (n - 1))
2938-- Pair each element in a stream with its index, starting from the
2939-- given index @n@ and counting down.
2942-- > S.toList $ S.indexedR 10 $ S.fromList "hello"
2943-- [(10,'h'),(9,'e'),(8,'l'),(7,'l'),(6,'o')]
2947{-# INLINE indexedR #-}
2948indexedR :: (IsStream t, Monad m) => Int -> t m a -> t m (Int, a)
2949indexedR n = fromStreamD . D.indexedR n . toStreamD
2951-- Note: The timestamp stream must be the second stream in the zip so that the
2952-- timestamp is generated after generating the stream element and not before.
2953-- If we do not do that then the following example will generate the same
2954-- timestamp for first two elements:
2956-- S.mapM_ print $ S.timestamped $ S.delay $ S.enumerateFromTo 1 3
2958-- | Pair each element in a stream with an absolute timestamp, using a clock of
2959-- specified granularity. The timestamp is generated just before the element
2963-- >>> S.mapM_ print $ S.timestampWith 0.01 $ S.delay 1 $ S.enumerateFromTo 1 3
2968{-# INLINE timestampWith #-}
2969timestampWith :: (IsStream t, MonadAsync m, Functor (t m))
2970 => Double -> t m a -> t m (AbsTime, a)
2971timestampWith g stream = Z.zipWith (flip (,)) stream (absTimesWith g)
2973-- TBD: check performance vs a custom implementation without using zipWith.
2975-- | Pair each element in a stream with an absolute timestamp, using a clock of
2976-- 10 ms granularity. The timestamp is generated just before the element is
2980-- >>> S.mapM_ print $ S.timestamped $ S.delay 1 $ S.enumerateFromTo 1 3
2981-- (AbsTime (TimeSpec {sec = 2460689, nsec = 641121000}),1)
2982-- (AbsTime (TimeSpec {sec = 2460690, nsec = 639334000}),2)
2983-- (AbsTime (TimeSpec {sec = 2460691, nsec = 644479000}),3)
2988{-# INLINE timestamped #-}
2989timestamped :: (IsStream t, MonadAsync m, Functor (t m))
2990 => t m a -> t m (AbsTime, a)
2991timestamped = timestampWith 0.01
2993-- | Pair each element in a stream with relative times starting from 0, using a
2994-- clock with the specified granularity. The time is measured just before the
2995-- element is consumed.
2998-- >>> S.mapM_ print $ S.timeIndexWith 0.01 $ S.delay 1 $ S.enumerateFromTo 1 3
3003{-# INLINE timeIndexWith #-}
3004timeIndexWith :: (IsStream t, MonadAsync m, Functor (t m))
3005 => Double -> t m a -> t m (RelTime64, a)
3006timeIndexWith g stream = Z.zipWith (flip (,)) stream (relTimesWith g)
3008-- | Pair each element in a stream with relative times starting from 0, using a
3009-- 10 ms granularity clock. The time is measured just before the element is
3013-- >>> S.mapM_ print $ S.timeIndexed $ S.delay 1 $ S.enumerateFromTo 1 3
3014-- (RelTime64 (NanoSecond64 0),1)
3015-- (RelTime64 (NanoSecond64 996239000),2)
3016-- (RelTime64 (NanoSecond64 1996712000),3)
3021{-# INLINE timeIndexed #-}
3022timeIndexed :: (IsStream t, MonadAsync m, Functor (t m))
3023 => t m a -> t m (RelTime64, a)
3024timeIndexed = timeIndexWith 0.01
3026------------------------------------------------------------------------------
3028------------------------------------------------------------------------------
3030-- | Compare two streams for equality using an equality function.
3033{-# INLINABLE eqBy #-}
3034eqBy :: (IsStream t, Monad m) => (a -> b -> Bool) -> t m a -> t m b -> m Bool
3037-- | Compare two streams lexicographically using a comparison function.
3040{-# INLINABLE cmpBy #-}
3042 :: (IsStream t, Monad m)
3043 => (a -> b -> Ordering) -> t m a -> t m b -> m Ordering
3046------------------------------------------------------------------------------
3048------------------------------------------------------------------------------
3050-- | Merge two streams using a comparison function. The head elements of both
3051-- the streams are compared and the smaller of the two elements is emitted, if
3052-- both elements are equal then the element from the first stream is used
3055-- If the streams are sorted in ascending order, the resulting stream would
3056-- also remain sorted in ascending order.
3059-- > S.toList $ S.mergeBy compare (S.fromList [1,3,5]) (S.fromList [2,4,6,8])
3064{-# INLINABLE mergeBy #-}
3066 (IsStream t, Monad m) => (a -> a -> Ordering) -> t m a -> t m a -> t m a
3067mergeBy f m1 m2 = fromStreamS $ S.mergeBy f (toStreamS m1) (toStreamS m2)
3069-- | Like 'mergeBy' but with a monadic comparison function.
3071-- Merge two streams randomly:
3074-- > randomly _ _ = randomIO >>= \x -> return $ if x then LT else GT
3075-- > S.toList $ S.mergeByM randomly (S.fromList [1,1,1,1]) (S.fromList [2,2,2,2])
3079-- Merge two streams in a proportion of 2:1:
3082-- proportionately m n = do
3083-- ref <- newIORef $ cycle $ concat [replicate m LT, replicate n GT]
3084-- return $ \\_ _ -> do
3085-- r <- readIORef ref
3086-- writeIORef ref $ tail r
3090-- f <- proportionately 2 1
3091-- xs <- S.toList $ S.mergeByM f (S.fromList [1,1,1,1,1,1]) (S.fromList [2,2,2])
3095-- [1,1,2,1,1,2,1,1,2]
3099{-# INLINABLE mergeByM #-}
3101 :: (IsStream t, Monad m)
3102 => (a -> a -> m Ordering) -> t m a -> t m a -> t m a
3103mergeByM f m1 m2 = fromStreamS $ S.mergeByM f (toStreamS m1) (toStreamS m2)
3106-- | Like 'mergeByM' but stops merging as soon as any of the two streams stops.
3107{-# INLINABLE mergeEndByAny #-}
3109 :: (IsStream t, Monad m)
3110 => (a -> a -> m Ordering) -> t m a -> t m a -> t m a
3111mergeEndByAny f m1 m2 = fromStreamD $
3112 D.mergeEndByAny f (toStreamD m1) (toStreamD m2)
3114-- Like 'mergeByM' but stops merging as soon as the first stream stops.
3115{-# INLINABLE mergeEndByFirst #-}
3117 :: (IsStream t, Monad m)
3118 => (a -> a -> m Ordering) -> t m a -> t m a -> t m a
3119mergeEndByFirst f m1 m2 = fromStreamS $
3120 D.mergeEndByFirst f (toStreamD m1) (toStreamD m2)
3123-- Holding this back for now, we may want to use the name "merge" differently
3125-- | Same as @'mergeBy' 'compare'@.
3128-- > S.toList $ S.merge (S.fromList [1,3,5]) (S.fromList [2,4,6,8])
3133{-# INLINABLE merge #-}
3135 (IsStream t, Monad m, Ord a) => t m a -> t m a -> t m a
3136merge = mergeBy compare
3139-- | Like 'mergeBy' but merges concurrently (i.e. both the elements being
3140-- merged are generated concurrently).
3143{-# INLINE mergeAsyncBy #-}
3144mergeAsyncBy :: (IsStream t, MonadAsync m)
3145 => (a -> a -> Ordering) -> t m a -> t m a -> t m a
3146mergeAsyncBy f = mergeAsyncByM (\a b -> return $ f a b)
3148-- | Like 'mergeByM' but merges concurrently (i.e. both the elements being
3149-- merged are generated concurrently).
3152{-# INLINE mergeAsyncByM #-}
3153mergeAsyncByM :: (IsStream t, MonadAsync m)
3154 => (a -> a -> m Ordering) -> t m a -> t m a -> t m a
3155mergeAsyncByM f m1 m2 = fromStreamD $
3156 D.mergeByM f (D.mkParallelD $ toStreamD m1) (D.mkParallelD $ toStreamD m2)
3158------------------------------------------------------------------------------
3160------------------------------------------------------------------------------
3162-- | @concatMapWith merge map stream@ is a two dimensional looping combinator.
3163-- The first argument specifies a merge or concat function that is used to
3164-- merge the streams generated by applying the second argument i.e. the @map@
3165-- function to each element of the input stream. The concat function could be
3166-- 'serial', 'parallel', 'async', 'ahead' or any other zip or merge function
3167-- and the second argument could be any stream generation function using a
3170-- /Compare 'foldMapWith'/
3174-- /Since: 0.8.0 (signature change)/
3175{-# INLINE concatMapWith #-}
3178 => (t m b -> t m b -> t m b)
3182concatMapWith = K.concatMapBy
3184-- | Like 'concatMapWith' but carries a state which can be used to share
3185-- information across multiple steps of concat.
3188-- concatSmapMWith combine f initial = concatMapWith combine id . smapM f initial
3193{-# INLINE concatSmapMWith #-}
3195 :: (IsStream t, Monad m)
3196 => (t m b -> t m b -> t m b)
3197 -> (s -> a -> m (s, t m b))
3201concatSmapMWith combine f initial = concatMapWith combine id . smapM f initial
3203-- | Map a stream producing function on each element of the stream and then
3204-- flatten the results into a single stream.
3207-- concatMap f = 'concat . map f'
3208-- concatMap = 'concatMapWith' 'Serial.serial'
3209-- concatMap f = 'concatMapM' (return . f)
3210-- concatMap f = 'concatUnfold' (UF.lmap f UF.fromStream)
3214{-# INLINE concatMap #-}
3215concatMap ::(IsStream t, Monad m) => (a -> t m b) -> t m a -> t m b
3216concatMap f m = fromStreamD $ D.concatMap (toStreamD . f) (toStreamD m)
3218-- | Flatten a stream of streams to a single stream.
3221-- concat = concatMap id
3225{-# INLINE concat #-}
3226concat :: (IsStream t, Monad m) => t m (t m a) -> t m a
3227concat = concatMap id
3229-- | Append the outputs of two streams, yielding all the elements from the
3230-- first stream and then yielding all the elements from the second stream.
3232-- IMPORTANT NOTE: This could be 100x faster than @serial/<>@ for appending a
3233-- few (say 100) streams because it can fuse via stream fusion. However, it
3234-- does not scale for a large number of streams (say 1000s) and becomes
3235-- qudartically slow. Therefore use this for custom appending of a few streams
3236-- but use 'concatMap' or 'concatMapWith serial' for appending @n@ streams or
3237-- infinite containers of streams.
3240{-# INLINE append #-}
3241append ::(IsStream t, Monad m) => t m b -> t m b -> t m b
3242append m1 m2 = fromStreamD $ D.append (toStreamD m1) (toStreamD m2)
3244-- XXX Same as 'wSerial'. We should perhaps rename wSerial to interleave.
3245-- XXX Document the interleaving behavior of side effects in all the
3246-- interleaving combinators.
3247-- XXX Write time-domain equivalents of these. In the time domain we can
3248-- interleave two streams such that the value of second stream is always taken
3249-- from its last value even if no new value is being yielded, like
3250-- zipWithLatest. It would be something like interleaveWithLatest.
3252-- | Interleaves the outputs of two streams, yielding elements from each stream
3253-- alternately, starting from the first stream. If any of the streams finishes
3254-- early the other stream continues alone until it too finishes.
3256-- >>> :set -XOverloadedStrings
3257-- >>> interleave "ab" ",,,," :: SerialT Identity Char
3259-- >>> interleave "abcd" ",," :: SerialT Identity Char
3262-- 'interleave' is dual to 'interleaveMin', it can be called @interleaveMax@.
3264-- Do not use at scale in concatMapWith.
3267{-# INLINE interleave #-}
3268interleave ::(IsStream t, Monad m) => t m b -> t m b -> t m b
3269interleave m1 m2 = fromStreamD $ D.interleave (toStreamD m1) (toStreamD m2)
3271-- | Interleaves the outputs of two streams, yielding elements from each stream
3272-- alternately, starting from the first stream. As soon as the first stream
3273-- finishes, the output stops, discarding the remaining part of the second
3274-- stream. In this case, the last element in the resulting stream would be from
3275-- the second stream. If the second stream finishes early then the first stream
3276-- still continues to yield elements until it finishes.
3278-- >>> :set -XOverloadedStrings
3279-- >>> interleaveSuffix "abc" ",,,," :: SerialT Identity Char
3281-- >>> interleaveSuffix "abc" "," :: SerialT Identity Char
3284-- 'interleaveSuffix' is a dual of 'interleaveInfix'.
3286-- Do not use at scale in concatMapWith.
3289{-# INLINE interleaveSuffix #-}
3290interleaveSuffix ::(IsStream t, Monad m) => t m b -> t m b -> t m b
3291interleaveSuffix m1 m2 =
3292 fromStreamD $ D.interleaveSuffix (toStreamD m1) (toStreamD m2)
3294-- | Interleaves the outputs of two streams, yielding elements from each stream
3295-- alternately, starting from the first stream and ending at the first stream.
3296-- If the second stream is longer than the first, elements from the second
3297-- stream are infixed with elements from the first stream. If the first stream
3298-- is longer then it continues yielding elements even after the second stream
3301-- >>> :set -XOverloadedStrings
3302-- >>> interleaveInfix "abc" ",,,," :: SerialT Identity Char
3304-- >>> interleaveInfix "abc" "," :: SerialT Identity Char
3307-- 'interleaveInfix' is a dual of 'interleaveSuffix'.
3309-- Do not use at scale in concatMapWith.
3312{-# INLINE interleaveInfix #-}
3313interleaveInfix ::(IsStream t, Monad m) => t m b -> t m b -> t m b
3314interleaveInfix m1 m2 =
3315 fromStreamD $ D.interleaveInfix (toStreamD m1) (toStreamD m2)
3317-- | Interleaves the outputs of two streams, yielding elements from each stream
3318-- alternately, starting from the first stream. The output stops as soon as any
3319-- of the two streams finishes, discarding the remaining part of the other
3320-- stream. The last element of the resulting stream would be from the longer
3323-- >>> :set -XOverloadedStrings
3324-- >>> interleaveMin "ab" ",,,," :: SerialT Identity Char
3326-- >>> interleaveMin "abcd" ",," :: SerialT Identity Char
3329-- 'interleaveMin' is dual to 'interleave'.
3331-- Do not use at scale in concatMapWith.
3334{-# INLINE interleaveMin #-}
3335interleaveMin ::(IsStream t, Monad m) => t m b -> t m b -> t m b
3336interleaveMin m1 m2 = fromStreamD $ D.interleaveMin (toStreamD m1) (toStreamD m2)
3338-- | Schedule the execution of two streams in a fair round-robin manner,
3339-- executing each stream once, alternately. Execution of a stream may not
3340-- necessarily result in an output, a stream may chose to @Skip@ producing an
3341-- element until later giving the other stream a chance to run. Therefore, this
3342-- combinator fairly interleaves the execution of two streams rather than
3343-- fairly interleaving the output of the two streams. This can be useful in
3344-- co-operative multitasking without using explicit threads. This can be used
3345-- as an alternative to `async`.
3347-- Do not use at scale in concatMapWith.
3350{-# INLINE roundrobin #-}
3351roundrobin ::(IsStream t, Monad m) => t m b -> t m b -> t m b
3352roundrobin m1 m2 = fromStreamD $ D.roundRobin (toStreamD m1) (toStreamD m2)
3354-- | Map a stream producing monadic function on each element of the stream
3355-- and then flatten the results into a single stream. Since the stream
3356-- generation function is monadic, unlike 'concatMap', it can produce an
3357-- effect at the beginning of each iteration of the inner loop.
3360{-# INLINE concatMapM #-}
3361concatMapM :: (IsStream t, Monad m) => (a -> m (t m b)) -> t m a -> t m b
3362concatMapM f m = fromStreamD $ D.concatMapM (fmap toStreamD . f) (toStreamD m)
3364-- | Given a stream value in the underlying monad, lift and join the underlying
3365-- monad with the stream monad.
3368-- concatM = concat . yieldM
3369-- concatM = concat . lift -- requires @(MonadTrans t)@
3370-- concatM = join . lift -- requires @(MonadTrans t@, @Monad (t m))@
3373-- See also: 'concat', 'sequence'
3377{-# INLINE concatM #-}
3378concatM :: (IsStream t, Monad m) => m (t m a) -> t m a
3379concatM generator = concatMapM (\() -> generator) (yield ())
3381-- | Like 'concatMap' but uses an 'Unfold' for stream generation. Unlike
3382-- 'concatMap' this can fuse the 'Unfold' code with the inner loop and
3383-- therefore provide many times better performance.
3386{-# INLINE concatUnfold #-}
3387concatUnfold ::(IsStream t, Monad m) => Unfold m a b -> t m a -> t m b
3388concatUnfold u m = fromStreamD $ D.concatMapU u (toStreamD m)
3390-- | Like 'concatUnfold' but interleaves the streams in the same way as
3391-- 'interleave' behaves instead of appending them.
3394{-# INLINE concatUnfoldInterleave #-}
3395concatUnfoldInterleave ::(IsStream t, Monad m)
3396 => Unfold m a b -> t m a -> t m b
3397concatUnfoldInterleave u m =
3398 fromStreamD $ D.concatUnfoldInterleave u (toStreamD m)
3400-- | Like 'concatUnfold' but executes the streams in the same way as
3404{-# INLINE concatUnfoldRoundrobin #-}
3405concatUnfoldRoundrobin ::(IsStream t, Monad m)
3406 => Unfold m a b -> t m a -> t m b
3407concatUnfoldRoundrobin u m =
3408 fromStreamD $ D.concatUnfoldRoundrobin u (toStreamD m)
3410-- XXX we can swap the order of arguments to gintercalate so that the
3411-- definition of concatUnfold becomes simpler? The first stream should be
3412-- infixed inside the second one. However, if we change the order in
3413-- "interleave" as well similarly, then that will make it a bit unintuitive.
3415-- > concatUnfold unf str =
3416-- > gintercalate unf str (UF.nilM (\_ -> return ())) (repeat ())
3418-- | 'interleaveInfix' followed by unfold and concat.
3421{-# INLINE gintercalate #-}
3423 :: (IsStream t, Monad m)
3424 => Unfold m a c -> t m a -> Unfold m b c -> t m b -> t m c
3425gintercalate unf1 str1 unf2 str2 =
3426 D.fromStreamD $ D.gintercalate
3427 unf1 (D.toStreamD str1)
3428 unf2 (D.toStreamD str2)
3430-- XXX The order of arguments in "intercalate" is consistent with the list
3431-- intercalate but inconsistent with gintercalate and other stream interleaving
3432-- combinators. We can change the order of the arguments in other combinators
3433-- but then 'interleave' combinator may become a bit unintuitive because we
3434-- will be starting with the second stream.
3436-- > intercalate seed unf str = gintercalate unf str unf (repeatM seed)
3437-- > intercalate a unf str = concatUnfold unf $ intersperse a str
3439-- | 'intersperse' followed by unfold and concat.
3441-- > unwords = intercalate " " UF.fromList
3443-- >>> intercalate " " UF.fromList ["abc", "def", "ghi"]
3447{-# INLINE intercalate #-}
3448intercalate :: (IsStream t, Monad m)
3449 => b -> Unfold m b c -> t m b -> t m c
3450intercalate seed unf str = D.fromStreamD $
3451 D.concatMapU unf $ D.intersperse seed (toStreamD str)
3453-- > interpose x unf str = gintercalate unf str UF.identity (repeat x)
3455-- | Unfold the elements of a stream, intersperse the given element between the
3456-- unfolded streams and then concat them into a single stream.
3458-- > unwords = S.interpose ' '
3461{-# INLINE interpose #-}
3462interpose :: (IsStream t, Monad m)
3463 => c -> Unfold m b c -> t m b -> t m c
3464interpose x unf str =
3465 D.fromStreamD $ D.interpose (return x) unf (D.toStreamD str)
3467-- | 'interleaveSuffix' followed by unfold and concat.
3470{-# INLINE gintercalateSuffix #-}
3472 :: (IsStream t, Monad m)
3473 => Unfold m a c -> t m a -> Unfold m b c -> t m b -> t m c
3474gintercalateSuffix unf1 str1 unf2 str2 =
3475 D.fromStreamD $ D.gintercalateSuffix
3476 unf1 (D.toStreamD str1)
3477 unf2 (D.toStreamD str2)
3479-- > intercalateSuffix seed unf str = gintercalateSuffix unf str unf (repeatM seed)
3480-- > intercalateSuffix a unf str = concatUnfold unf $ intersperseSuffix a str
3482-- | 'intersperseSuffix' followed by unfold and concat.
3484-- > unlines = intercalateSuffix "\n" UF.fromList
3486-- >>> intercalate "\n" UF.fromList ["abc", "def", "ghi"]
3487-- > "abc\ndef\nghi\n"
3490{-# INLINE intercalateSuffix #-}
3491intercalateSuffix :: (IsStream t, Monad m)
3492 => b -> Unfold m b c -> t m b -> t m c
3493intercalateSuffix seed unf str = fromStreamD $ D.concatMapU unf
3494 $ D.intersperseSuffix (return seed) (D.toStreamD str)
3496-- interposeSuffix x unf str = gintercalateSuffix unf str UF.identity (repeat x)
3498-- | Unfold the elements of a stream, append the given element after each
3499-- unfolded stream and then concat them into a single stream.
3501-- > unlines = S.interposeSuffix '\n'
3504{-# INLINE interposeSuffix #-}
3505interposeSuffix :: (IsStream t, Monad m)
3506 => c -> Unfold m b c -> t m b -> t m c
3507interposeSuffix x unf str =
3508 D.fromStreamD $ D.interposeSuffix (return x) unf (D.toStreamD str)
3510------------------------------------------------------------------------------
3512------------------------------------------------------------------------------
3514-- | Like 'iterateM' but iterates after mapping a stream generator on the
3517-- Yield an input element in the output stream, map a stream generator on it
3518-- and then do the same on the resulting stream. This can be used for a depth
3519-- first traversal of a tree like structure.
3521-- Note that 'iterateM' is a special case of 'iterateMapWith':
3524-- iterateM f = iterateMapWith serial (yieldM . f) . yieldM
3527-- It can be used to traverse a tree structure. For example, to list a
3531-- Stream.iterateMapWith Stream.serial
3532-- (either Dir.toEither (const nil))
3533-- (yield (Left "tmp"))
3538{-# INLINE iterateMapWith #-}
3541 => (t m a -> t m a -> t m a)
3545iterateMapWith combine f = concatMapWith combine go
3547 go x = yield x `combine` concatMapWith combine go (f x)
3550{-# INLINE iterateUnfold #-}
3551iterateUnfold :: (IsStream t, MonadAsync m)
3552 => Unfold m a a -> t m a -> t m a
3553iterateUnfold unf xs = undefined
3556------------------------------------------------------------------------------
3558------------------------------------------------------------------------------
3560-- To traverse graphs we need a state to be carried around in the traversal.
3561-- For example, we can use a hashmap to store the visited status of nodes.
3563-- | Like 'iterateMap' but carries a state in the stream generation function.
3564-- This can be used to traverse graph like structures, we can remember the
3565-- visited nodes in the state to avoid cycles.
3567-- Note that a combination of 'iterateMap' and 'usingState' can also be used to
3568-- traverse graphs. However, this function provides a more localized state
3569-- instead of using a global state.
3575{-# INLINE iterateSmapMWith #-}
3577 :: (IsStream t, Monad m)
3578 => (t m a -> t m a -> t m a)
3579 -> (b -> a -> m (b, t m a))
3583iterateSmapMWith combine f initial stream =
3584 concatMap (\b -> concatMapWith combine (go b) stream) (yieldM initial)
3588 go b a = yield a `combine` feedback b a
3592 (\(b1, s) -> concatMapWith combine (go b1) s)
3595------------------------------------------------------------------------------
3597------------------------------------------------------------------------------
3599-- | Discard 'Right's and unwrap 'Left's in an 'Either' stream.
3603lefts :: (IsStream t, Monad m, Functor (t m)) => t m (Either a b) -> t m a
3604lefts = fmap (fromLeft undefined) . filter isLeft
3606-- | Discard 'Left's and unwrap 'Right's in an 'Either' stream.
3610rights :: (IsStream t, Monad m, Functor (t m)) => t m (Either a b) -> t m b
3611rights = fmap (fromRight undefined) . filter isRight
3613-- | In an 'Either' stream iterate on 'Left's. This is a special case of
3617-- iterateMapLeftsWith combine f = iterateMapWith combine (either f (const nil))
3620-- To traverse a directory tree:
3623-- iterateMapLeftsWith serial Dir.toEither (yield (Left "tmp"))
3628{-# INLINE iterateMapLeftsWith #-}
3631 => (t m (Either a b) -> t m (Either a b) -> t m (Either a b))
3632 -> (a -> t m (Either a b))
3635iterateMapLeftsWith combine f = iterateMapWith combine (either f (const K.nil))
3637------------------------------------------------------------------------------
3639------------------------------------------------------------------------------
3641-- Splitting operations that take a predicate and a Fold can be
3642-- expressed using parseMany. Operations like chunksOf, intervalsOf, split*,
3643-- can be expressed using parseMany when used with an appropriate Parser.
3645-- XXX We need takeGE/takeBetween to implement "some" using "many".
3647-- | Apply a 'Parser' repeatedly on a stream and emit the parsed values in the
3650-- This is the streaming equivalent of the 'Streamly.Internal.Data.Parser.many'
3653-- >>> S.toList $ S.parseMany (PR.take 2 $ PR.fromFold FL.sum) $ S.fromList [1..10]
3656-- >>> S.toList $ S.parseMany (PR.line FL.toList) $ S.fromList "hello\nworld"
3657-- > ["hello\n","world"]
3661{-# INLINE parseMany #-}
3663 :: (IsStream t, MonadThrow m)
3668 D.fromStreamD $ D.parseMany (PRK.fromParserK p) (D.toStreamD m)
3670{-# INLINE parseManyD #-}
3672 :: (IsStream t, MonadThrow m)
3677 D.fromStreamD $ D.parseMany p (D.toStreamD m)
3679-- | @parseManyTill collect test stream@ tries the parser @test@ on the input,
3680-- if @test@ fails it backtracks and tries @collect@, after @collect@ succeeds
3681-- @test@ is tried again and so on. The parser stops when @test@ succeeds. The
3682-- output of @test@ is discarded and the output of @collect@ is emitted in the
3683-- output stream. The parser fails if @collect@ fails.
3687{-# INLINE parseManyTill #-}
3689 -- (IsStream t, MonadThrow m) =>
3694parseManyTill = undefined
3696-- | Iterate a parser generating function on a stream. The initial value @b@ is
3697-- used to generate the first parser, the parser is applied on the stream and
3698-- the result is used to generate the next parser and so on.
3700-- >>> S.toList $ S.map getSum $ S.parseIterate (\b -> PR.take 2 (FL.mconcatTo b)) 0 $ S.map Sum $ S.fromList [1..10]
3701-- > [3,10,21,36,55,55]
3703-- This is the streaming equivalent of monad like sequenced application of
3704-- parsers where next parser is dependent on the previous parser.
3708{-# INLINE parseIterate #-}
3710 :: (IsStream t, MonadThrow m)
3711 => (b -> Parser m a b)
3715parseIterate f i m = D.fromStreamD $
3716 D.parseIterate (PRK.fromParserK . f) i (D.toStreamD m)
3718------------------------------------------------------------------------------
3719-- Grouping/Splitting
3720------------------------------------------------------------------------------
3722------------------------------------------------------------------------------
3723-- Grouping without looking at elements
3724------------------------------------------------------------------------------
3726------------------------------------------------------------------------------
3728------------------------------------------------------------------------------
3731------------------------------------------------------------------------------
3733------------------------------------------------------------------------------
3735------------------------------------------------------------------------------
3736-- Generalized grouping
3737------------------------------------------------------------------------------
3739-- This combinator is the most general grouping combinator and can be used to
3740-- implement all other grouping combinators.
3742-- XXX check if this can implement the splitOn combinator i.e. we can slide in
3743-- new elements, slide out old elements and incrementally compute the hash.
3744-- Also, can we implement the windowed classification combinators using this?
3746-- In fact this is a parse. Instead of using a special return value in the fold
3747-- we are using a mapping function.
3749-- Note that 'scanl'' (usually followed by a map to extract the desired value
3750-- from the accumulator) can be used to realize many implementations e.g. a
3751-- sliding window implementation. A scan followed by a mapMaybe is also a good
3752-- pattern to express many problems where we want to emit a filtered output and
3753-- not emit an output on every input.
3755-- Passing on of the initial accumulator value to the next fold is equivalent
3756-- to returning the leftover concept.
3759-- | @groupScan splitter fold stream@ folds the input stream using @fold@.
3760-- @splitter@ is applied on the accumulator of the fold every time an item is
3761-- consumed by the fold. The fold continues until @splitter@ returns a 'Just'
3762-- value. A 'Just' result from the @splitter@ specifies a result to be emitted
3763-- in the output stream and the initial value of the accumulator for the next
3764-- group's fold. This allows us to control whether to start fresh for the next
3765-- fold or to continue from the previous fold's output.
3767{-# INLINE groupScan #-}
3769 :: (IsStream t, Monad m)
3770 => (x -> m (Maybe (b, x))) -> Fold m a x -> t m a -> t m b
3771groupScan split fold m = undefined
3774-- | Group the input stream into groups of @n@ elements each and then fold each
3775-- group using the provided fold function.
3777-- >> S.toList $ S.chunksOf 2 FL.sum (S.enumerateFromTo 1 10)
3780-- This can be considered as an n-fold version of 'ltake' where we apply
3781-- 'ltake' repeatedly on the leftover stream until the stream exhausts.
3784{-# INLINE chunksOf #-}
3786 :: (IsStream t, Monad m)
3787 => Int -> Fold m a b -> t m a -> t m b
3788chunksOf n f m = D.fromStreamD $ D.groupsOf n f (D.toStreamD m)
3793{-# INLINE chunksOf2 #-}
3795 :: (IsStream t, Monad m)
3796 => Int -> m c -> Fold2 m c a b -> t m a -> t m b
3797chunksOf2 n action f m = D.fromStreamD $ D.groupsOf2 n action f (D.toStreamD m)
3799-- | @arraysOf n stream@ groups the elements in the input stream into arrays of
3800-- @n@ elements each.
3802-- Same as the following but may be more efficient:
3804-- > arraysOf n = S.chunksOf n (A.writeN n)
3807{-# INLINE arraysOf #-}
3808arraysOf :: (IsStream t, MonadIO m, Storable a)
3809 => Int -> t m a -> t m (Array a)
3810arraysOf n = chunksOf n (writeNUnsafe n)
3812-- XXX we can implement this by repeatedly applying the 'lrunFor' fold.
3813-- XXX add this example after fixing the serial stream rate control
3814-- >>> S.toList $ S.take 5 $ intervalsOf 1 FL.sum $ constRate 2 $ S.enumerateFrom 1
3817-- | Group the input stream into windows of @n@ second each and then fold each
3818-- group using the provided fold function.
3821{-# INLINE intervalsOf #-}
3823 :: (IsStream t, MonadAsync m)
3824 => Double -> Fold m a b -> t m a -> t m b
3826 splitWithSuffix isNothing (FL.lcatMaybes f)
3827 (interjectSuffix n (return Nothing) (Serial.map Just xs))
3829------------------------------------------------------------------------------
3831------------------------------------------------------------------------------
3833-- | @groupsBy cmp f $ S.fromList [a,b,c,...]@ assigns the element @a@ to the
3834-- first group, if @b \`cmp` a@ is 'True' then @b@ is also assigned to the same
3835-- group. If @c \`cmp` a@ is 'True' then @c@ is also assigned to the same
3836-- group and so on. When the comparison fails a new group is started. Each
3837-- group is folded using the fold @f@ and the result of the fold is emitted in
3838-- the output stream.
3840-- >>> S.toList $ S.groupsBy (>) FL.toList $ S.fromList [1,3,7,0,2,5]
3841-- > [[1,3,7],[0,2,5]]
3844{-# INLINE groupsBy #-}
3846 :: (IsStream t, Monad m)
3851groupsBy cmp f m = D.fromStreamD $ D.groupsBy cmp f (D.toStreamD m)
3853-- | Unlike @groupsBy@ this function performs a rolling comparison of two
3854-- successive elements in the input stream. @groupsByRolling cmp f $ S.fromList
3855-- [a,b,c,...]@ assigns the element @a@ to the first group, if @a \`cmp` b@ is
3856-- 'True' then @b@ is also assigned to the same group. If @b \`cmp` c@ is
3857-- 'True' then @c@ is also assigned to the same group and so on. When the
3858-- comparison fails a new group is started. Each group is folded using the fold
3861-- >>> S.toList $ S.groupsByRolling (\a b -> a + 1 == b) FL.toList $ S.fromList [1,2,3,7,8,9]
3862-- > [[1,2,3],[7,8,9]]
3865{-# INLINE groupsByRolling #-}
3867 :: (IsStream t, Monad m)
3872groupsByRolling cmp f m = D.fromStreamD $ D.groupsRollingBy cmp f (D.toStreamD m)
3875-- > groups = groupsBy (==)
3876-- > groups = groupsByRolling (==)
3878-- Groups contiguous spans of equal elements together in individual groups.
3880-- >>> S.toList $ S.groups FL.toList $ S.fromList [1,1,2,2]
3884groups :: (IsStream t, Monad m, Eq a) => Fold m a b -> t m a -> t m b
3885groups = groupsBy (==)
3887------------------------------------------------------------------------------
3888-- N-ary split on a predicate
3889------------------------------------------------------------------------------
3891-- TODO: Use a Splitter configuration similar to the "split" package to make it
3892-- possible to express all splitting combinations. In general, we can have
3893-- infix/suffix/prefix/condensing of separators, dropping both leading/trailing
3894-- separators. We can have a single split operation taking the splitter config
3897-- | Split on an infixed separator element, dropping the separator. Splits the
3898-- stream on separator elements determined by the supplied predicate, separator
3899-- is considered as infixed between two segments, if one side of the separator
3900-- is missing then it is parsed as an empty stream. The supplied 'Fold' is
3901-- applied on the split segments. With '-' representing non-separator elements
3902-- and '.' as separator, 'splitOn' splits as follows:
3905-- "--.--" => "--" "--"
3910-- @splitOn (== x)@ is an inverse of @intercalate (S.yield x)@
3912-- Let's use the following definition for illustration:
3914-- > splitOn' p xs = S.toList $ S.splitOn p (FL.toList) (S.fromList xs)
3916-- >>> splitOn' (== '.') ""
3919-- >>> splitOn' (== '.') "."
3922-- >>> splitOn' (== '.') ".a"
3925-- >>> splitOn' (== '.') "a."
3928-- >>> splitOn' (== '.') "a.b"
3931-- >>> splitOn' (== '.') "a..b"
3936-- This can be considered as an n-fold version of 'breakOn' where we apply
3937-- 'breakOn' successively on the input stream, dropping the first element
3938-- of the second segment after each break.
3940{-# INLINE splitOn #-}
3942 :: (IsStream t, Monad m)
3943 => (a -> Bool) -> Fold m a b -> t m a -> t m b
3944splitOn predicate f m =
3945 D.fromStreamD $ D.splitBy predicate f (D.toStreamD m)
3947-- | Like 'splitOn' but the separator is considered as suffixed to the segments
3948-- in the stream. A missing suffix at the end is allowed. A separator at the
3949-- beginning is parsed as empty segment. With '-' representing elements and
3950-- '.' as separator, 'splitOnSuffix' splits as follows:
3953-- "--.--." => "--" "--"
3954-- "--.--" => "--" "--"
3958-- > splitOnSuffix' p xs = S.toList $ S.splitSuffixBy p (FL.toList) (S.fromList xs)
3960-- >>> splitOnSuffix' (== '.') ""
3963-- >>> splitOnSuffix' (== '.') "."
3966-- >>> splitOnSuffix' (== '.') "a"
3969-- >>> splitOnSuffix' (== '.') ".a"
3972-- >>> splitOnSuffix' (== '.') "a."
3975-- >>> splitOnSuffix' (== '.') "a.b"
3978-- >>> splitOnSuffix' (== '.') "a.b."
3981-- >>> splitOnSuffix' (== '.') "a..b.."
3984-- > lines = splitOnSuffix (== '\n')
3988-- This can be considered as an n-fold version of 'breakPost' where we apply
3989-- 'breakPost' successively on the input stream, dropping the first element
3990-- of the second segment after each break.
3992{-# INLINE splitOnSuffix #-}
3994 :: (IsStream t, Monad m)
3995 => (a -> Bool) -> Fold m a b -> t m a -> t m b
3996splitOnSuffix predicate f m =
3997 D.fromStreamD $ D.splitSuffixBy predicate f (D.toStreamD m)
3999-- | Like 'splitOn' after stripping leading, trailing, and repeated separators.
4000-- Therefore, @".a..b."@ with '.' as the separator would be parsed as
4001-- @["a","b"]@. In other words, its like parsing words from whitespace
4004-- > wordsBy' p xs = S.toList $ S.wordsBy p (FL.toList) (S.fromList xs)
4006-- >>> wordsBy' (== ',') ""
4009-- >>> wordsBy' (== ',') ","
4012-- >>> wordsBy' (== ',') ",a,,b,"
4015-- > words = wordsBy isSpace
4019-- It is equivalent to splitting in any of the infix/prefix/suffix styles
4020-- followed by removal of empty segments.
4021{-# INLINE wordsBy #-}
4023 :: (IsStream t, Monad m)
4024 => (a -> Bool) -> Fold m a b -> t m a -> t m b
4025wordsBy predicate f m =
4026 D.fromStreamD $ D.wordsBy predicate f (D.toStreamD m)
4028-- | Like 'splitOnSuffix' but keeps the suffix attached to the resulting
4031-- > splitWithSuffix' p xs = S.toList $ S.splitWithSuffix p (FL.toList) (S.fromList xs)
4033-- >>> splitWithSuffix' (== '.') ""
4036-- >>> splitWithSuffix' (== '.') "."
4039-- >>> splitWithSuffix' (== '.') "a"
4042-- >>> splitWithSuffix' (== '.') ".a"
4045-- >>> splitWithSuffix' (== '.') "a."
4048-- >>> splitWithSuffix' (== '.') "a.b"
4051-- >>> splitWithSuffix' (== '.') "a.b."
4054-- >>> splitWithSuffix' (== '.') "a..b.."
4055-- > ["a.",".","b.","."]
4059-- This can be considered as an n-fold version of 'breakPost' where we apply
4060-- 'breakPost' successively on the input stream.
4062{-# INLINE splitWithSuffix #-}
4064 :: (IsStream t, Monad m)
4065 => (a -> Bool) -> Fold m a b -> t m a -> t m b
4066splitWithSuffix predicate f m =
4067 D.fromStreamD $ D.splitSuffixBy' predicate f (D.toStreamD m)
4069------------------------------------------------------------------------------
4070-- Split on a delimiter sequence
4071------------------------------------------------------------------------------
4073-- Int list examples for splitOn:
4075-- >>> splitList [] [1,2,3,3,4]
4076-- > [[1],[2],[3],[3],[4]]
4078-- >>> splitList [5] [1,2,3,3,4]
4081-- >>> splitList [1] [1,2,3,3,4]
4084-- >>> splitList [4] [1,2,3,3,4]
4087-- >>> splitList [2] [1,2,3,3,4]
4090-- >>> splitList [3] [1,2,3,3,4]
4093-- >>> splitList [3,3] [1,2,3,3,4]
4096-- >>> splitList [1,2,3,3,4] [1,2,3,3,4]
4099-- | Like 'splitOn' but the separator is a sequence of elements instead of a
4102-- For illustration, let's define a function that operates on pure lists:
4105-- splitOnSeq' pat xs = S.toList $ S.splitOnSeq (A.fromList pat) (FL.toList) (S.fromList xs)
4108-- >>> splitOnSeq' "" "hello"
4109-- > ["h","e","l","l","o"]
4111-- >>> splitOnSeq' "hello" ""
4114-- >>> splitOnSeq' "hello" "hello"
4117-- >>> splitOnSeq' "x" "hello"
4120-- >>> splitOnSeq' "h" "hello"
4123-- >>> splitOnSeq' "o" "hello"
4126-- >>> splitOnSeq' "e" "hello"
4129-- >>> splitOnSeq' "l" "hello"
4132-- >>> splitOnSeq' "ll" "hello"
4135-- 'splitOnSeq' is an inverse of 'intercalate'. The following law always holds:
4137-- > intercalate . splitOn == id
4139-- The following law holds when the separator is non-empty and contains none of
4140-- the elements present in the input lists:
4142-- > splitOn . intercalate == id
4146-- XXX We can use a polymorphic vector implemented by Array# to represent the
4147-- sequence, that way we can avoid the Storable constraint. If we still need
4148-- Storable Array for performance, we can use a separate splitOnArray API for
4149-- that. We can also have an API where the sequence itself is a lazy stream, so
4150-- that we can search files in files for example.
4151{-# INLINE splitOnSeq #-}
4153 :: (IsStream t, MonadIO m, Storable a, Enum a, Eq a)
4154 => Array a -> Fold m a b -> t m a -> t m b
4155splitOnSeq patt f m = D.fromStreamD $ D.splitOn patt f (D.toStreamD m)
4158-- This can be implemented easily using Rabin Karp
4159-- | Split on any one of the given patterns.
4160{-# INLINE splitOnAny #-}
4162 :: (IsStream t, Monad m, Storable a, Integral a)
4163 => [Array a] -> Fold m a b -> t m a -> t m b
4164splitOnAny subseq f m = undefined -- D.fromStreamD $ D.splitOnAny f subseq (D.toStreamD m)
4167-- | Like 'splitSuffixBy' but the separator is a sequence of elements, instead
4168-- of a predicate for a single element.
4170-- > splitSuffixOn_ pat xs = S.toList $ S.splitSuffixOn (A.fromList pat) (FL.toList) (S.fromList xs)
4172-- >>> splitSuffixOn_ "." ""
4175-- >>> splitSuffixOn_ "." "."
4178-- >>> splitSuffixOn_ "." "a"
4181-- >>> splitSuffixOn_ "." ".a"
4184-- >>> splitSuffixOn_ "." "a."
4187-- >>> splitSuffixOn_ "." "a.b"
4190-- >>> splitSuffixOn_ "." "a.b."
4193-- >>> splitSuffixOn_ "." "a..b.."
4196-- > lines = splitSuffixOn "\n"
4199{-# INLINE splitOnSuffixSeq #-}
4201 :: (IsStream t, MonadIO m, Storable a, Enum a, Eq a)
4202 => Array a -> Fold m a b -> t m a -> t m b
4203splitOnSuffixSeq patt f m =
4204 D.fromStreamD $ D.splitSuffixOn False patt f (D.toStreamD m)
4207-- | Like 'splitOn' but drops any empty splits.
4209{-# INLINE wordsOn #-}
4211 :: (IsStream t, Monad m, Storable a, Eq a)
4212 => Array a -> Fold m a b -> t m a -> t m b
4213wordsOn subseq f m = undefined -- D.fromStreamD $ D.wordsOn f subseq (D.toStreamD m)
4216-- XXX use a non-monadic intersperse to remove the MonadAsync constraint.
4218-- | Like 'splitOnSeq' but splits the separator as well, as an infix token.
4220-- > splitOn'_ pat xs = S.toList $ S.splitOn' (A.fromList pat) (FL.toList) (S.fromList xs)
4222-- >>> splitOn'_ "" "hello"
4223-- > ["h","","e","","l","","l","","o"]
4225-- >>> splitOn'_ "hello" ""
4228-- >>> splitOn'_ "hello" "hello"
4231-- >>> splitOn'_ "x" "hello"
4234-- >>> splitOn'_ "h" "hello"
4237-- >>> splitOn'_ "o" "hello"
4240-- >>> splitOn'_ "e" "hello"
4243-- >>> splitOn'_ "l" "hello"
4244-- > ["he","l","","l","o"]
4246-- >>> splitOn'_ "ll" "hello"
4250{-# INLINE splitBySeq #-}
4252 :: (IsStream t, MonadAsync m, Storable a, Enum a, Eq a)
4253 => Array a -> Fold m a b -> t m a -> t m b
4254splitBySeq patt f m =
4255 intersperseM (fold f (A.toStream patt)) $ splitOnSeq patt f m
4257-- | Like 'splitSuffixOn' but keeps the suffix intact in the splits.
4259-- > splitSuffixOn'_ pat xs = S.toList $ FL.splitSuffixOn' (A.fromList pat) (FL.toList) (S.fromList xs)
4261-- >>> splitSuffixOn'_ "." ""
4264-- >>> splitSuffixOn'_ "." "."
4267-- >>> splitSuffixOn'_ "." "a"
4270-- >>> splitSuffixOn'_ "." ".a"
4273-- >>> splitSuffixOn'_ "." "a."
4276-- >>> splitSuffixOn'_ "." "a.b"
4279-- >>> splitSuffixOn'_ "." "a.b."
4282-- >>> splitSuffixOn'_ "." "a..b.."
4283-- > ["a.",".","b.","."]
4286{-# INLINE splitWithSuffixSeq #-}
4288 :: (IsStream t, MonadIO m, Storable a, Enum a, Eq a)
4289 => Array a -> Fold m a b -> t m a -> t m b
4290splitWithSuffixSeq patt f m =
4291 D.fromStreamD $ D.splitSuffixOn True patt f (D.toStreamD m)
4294-- This can be implemented easily using Rabin Karp
4295-- | Split post any one of the given patterns.
4296{-# INLINE splitSuffixOnAny #-}
4298 :: (IsStream t, Monad m, Storable a, Integral a)
4299 => [Array a] -> Fold m a b -> t m a -> t m b
4300splitSuffixOnAny subseq f m = undefined
4301 -- D.fromStreamD $ D.splitPostAny f subseq (D.toStreamD m)
4304------------------------------------------------------------------------------
4306------------------------------------------------------------------------------
4308-- | @splitInnerBy splitter joiner stream@ splits the inner containers @f a@ of
4309-- an input stream @t m (f a)@ using the @splitter@ function. Container
4310-- elements @f a@ are collected until a split occurs, then all the elements
4311-- before the split are joined using the @joiner@ function.
4313-- For example, if we have a stream of @Array Word8@, we may want to split the
4314-- stream into arrays representing lines separated by '\n' byte such that the
4315-- resulting stream after a split would be one array for each line.
4317-- CAUTION! This is not a true streaming function as the container size after
4318-- the split and merge may not be bounded.
4321{-# INLINE splitInnerBy #-}
4323 :: (IsStream t, Monad m)
4324 => (f a -> m (f a, Maybe (f a))) -- splitter
4325 -> (f a -> f a -> m (f a)) -- joiner
4328splitInnerBy splitter joiner xs =
4329 D.fromStreamD $ D.splitInnerBy splitter joiner $ D.toStreamD xs
4331-- | Like 'splitInnerBy' but splits assuming the separator joins the segment in
4335{-# INLINE splitInnerBySuffix #-}
4337 :: (IsStream t, Monad m, Eq (f a), Monoid (f a))
4338 => (f a -> m (f a, Maybe (f a))) -- splitter
4339 -> (f a -> f a -> m (f a)) -- joiner
4342splitInnerBySuffix splitter joiner xs =
4343 D.fromStreamD $ D.splitInnerBySuffix splitter joiner $ D.toStreamD xs
4345------------------------------------------------------------------------------
4346-- Reorder in sequence
4347------------------------------------------------------------------------------
4350-- Buffer until the next element in sequence arrives. The function argument
4351-- determines the difference in sequence numbers. This could be useful in
4352-- implementing sequenced streams, for example, TCP reassembly.
4353{-# INLINE reassembleBy #-}
4355 :: (IsStream t, Monad m)
4360reassembleBy = undefined
4363------------------------------------------------------------------------------
4365------------------------------------------------------------------------------
4367-- | Tap the data flowing through a stream into a 'Fold'. For example, you may
4368-- add a tap to log the contents flowing through the stream. The fold is used
4369-- only for effects, its result is discarded.
4374-- -----stream m a ---------------stream m a-----
4379-- > S.drain $ S.tap (FL.drainBy print) (S.enumerateFromTo 1 2)
4384-- Compare with 'trace'.
4388tap :: (IsStream t, Monad m) => FL.Fold m a b -> t m a -> t m a
4389tap f xs = D.fromStreamD $ D.tap f (D.toStreamD xs)
4391-- | @tapOffsetEvery offset n@ taps every @n@th element in the stream
4392-- starting at @offset@. @offset@ can be between @0@ and @n - 1@. Offset 0
4393-- means start at the first element in the stream. If the offset is outside
4394-- this range then @offset `mod` n@ is used as offset.
4397-- >>> S.drain $ S.tapOffsetEvery 0 2 (FL.mapM print FL.toList) $ S.enumerateFromTo 0 10
4403{-# INLINE tapOffsetEvery #-}
4404tapOffsetEvery :: (IsStream t, Monad m)
4405 => Int -> Int -> FL.Fold m a b -> t m a -> t m a
4406tapOffsetEvery offset n f xs =
4407 D.fromStreamD $ D.tapOffsetEvery offset n f (D.toStreamD xs)
4409-- | Redirect a copy of the stream to a supplied fold and run it concurrently
4410-- in an independent thread. The fold may buffer some elements. The buffer size
4411-- is determined by the prevailing 'maxBuffer' setting.
4416-- -----stream m a ---------------stream m a-----
4421-- > S.drain $ S.tapAsync (S.mapM_ print) (S.enumerateFromTo 1 2)
4426-- Exceptions from the concurrently running fold are propagated to the current
4427-- computation. Note that, because of buffering in the fold, exceptions may be
4428-- delayed and may not correspond to the current element being processed in the
4429-- parent stream, but we guarantee that before the parent stream stops the tap
4430-- finishes and all exceptions from it are drained.
4433-- Compare with 'tap'.
4436{-# INLINE tapAsync #-}
4437tapAsync :: (IsStream t, MonadAsync m) => FL.Fold m a b -> t m a -> t m a
4438tapAsync f xs = D.fromStreamD $ D.tapAsync f (D.toStreamD xs)
4440-- | @pollCounts predicate transform fold stream@ counts those elements in the
4441-- stream that pass the @predicate@. The resulting count stream is sent to
4442-- another thread which transforms it using @transform@ and then folds it using
4443-- @fold@. The thread is automatically cleaned up if the stream stops or
4444-- aborts due to exception.
4446-- For example, to print the count of elements processed every second:
4449-- > S.drain $ S.pollCounts (const True) (S.rollingMap (-) . S.delayPost 1) (FL.drainBy print)
4450-- $ S.enumerateFrom 0
4453-- Note: This may not work correctly on 32-bit machines.
4457{-# INLINE pollCounts #-}
4459 (IsStream t, MonadAsync m)
4461 -> (t m Int -> t m Int)
4465pollCounts predicate transf f xs =
4467 $ D.pollCounts predicate (D.toStreamD . transf . D.fromStreamD) f
4470-- | Calls the supplied function with the number of elements consumed
4471-- every @n@ seconds. The given function is run in a separate thread
4472-- until the end of the stream. In case there is an exception in the
4473-- stream the thread is killed during the next major GC.
4475-- Note: The action is not guaranteed to run if the main thread exits.
4478-- > delay n = threadDelay (round $ n * 1000000) >> return n
4479-- > S.drain $ S.tapRate 2 (\\n -> print $ show n ++ " elements processed") (delay 1 S.|: delay 0.5 S.|: delay 0.5 S.|: S.nil)
4480-- 2 elements processed
4481-- 1 elements processed
4484-- Note: This may not work correctly on 32-bit machines.
4487{-# INLINE tapRate #-}
4489 (IsStream t, MonadAsync m, MonadCatch m)
4494tapRate n f xs = D.fromStreamD $ D.tapRate n f $ D.toStreamD xs
4496-- | Apply a monadic function to each element flowing through the stream and
4497-- discard the results.
4500-- > S.drain $ S.trace print (S.enumerateFromTo 1 2)
4505-- Compare with 'tap'.
4509trace :: (IsStream t, MonadAsync m) => (a -> m b) -> t m a -> t m a
4510trace f = mapM (\x -> void (f x) >> return x)
4512-- | Perform a side effect before yielding each element of the stream and
4513-- discard the results.
4516-- > S.drain $ S.trace_ (print "got here") (S.enumerateFromTo 1 2)
4521-- See also: 'trace', 'interspersePrefix_'
4524{-# INLINE trace_ #-}
4525trace_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
4526trace_ eff = Serial.mapM (\x -> eff >> return x)
4528------------------------------------------------------------------------------
4529-- Windowed classification
4530------------------------------------------------------------------------------
4532-- We divide the stream into windows or chunks in space or time and each window
4533-- can be associated with a key, all events associated with a particular key in
4534-- the window can be folded to a single result. The stream can be split into
4535-- windows by size or by using a split predicate on the elements in the stream.
4536-- For example, when we receive a closing flag, we can close the window.
4538-- A "chunk" is a space window and a "session" is a time window. Are there any
4539-- other better short words to describe them. An alternative is to use
4540-- "swindow" and "twindow". Another word for "session" could be "spell".
4542-- TODO: To mark the position in space or time we can have Indexed or
4543-- TimeStamped types. That can make it easy to deal with the position indices
4546------------------------------------------------------------------------------
4547-- Keyed Sliding Windows
4548------------------------------------------------------------------------------
4551{-# INLINABLE classifySlidingChunks #-}
4552classifySlidingChunks
4553 :: (IsStream t, MonadAsync m, Ord k)
4554 => Int -- ^ window size
4555 -> Int -- ^ window slide
4556 -> Fold m a b -- ^ Fold to be applied to window events
4557 -> t m (k, a, Bool) -- ^ window key, data, close event
4559classifySlidingChunks wsize wslide (Fold step initial extract) str
4562-- XXX Another variant could be to slide the window on an event, e.g. in TCP we
4563-- slide the send window when an ack is received and we slide the receive
4564-- window when a sequence is complete. Sliding is stateful in case of TCP,
4565-- sliding releases the send buffer or makes data available to the user from
4566-- the receive buffer.
4567{-# INLINABLE classifySlidingSessions #-}
4568classifySlidingSessions
4569 :: (IsStream t, MonadAsync m, Ord k)
4570 => Double -- ^ timer tick in seconds
4571 -> Double -- ^ time window size
4572 -> Double -- ^ window slide
4573 -> Fold m a b -- ^ Fold to be applied to window events
4574 -> t m (k, a, Bool, AbsTime) -- ^ window key, data, close flag, timestamp
4576classifySlidingSessions tick interval slide (Fold step initial extract) str
4580------------------------------------------------------------------------------
4581-- Sliding Window Buffers
4582------------------------------------------------------------------------------
4584-- These buffered versions could be faster than concurrent incremental folds of
4585-- all overlapping windows as in many cases we may not need all the values to
4586-- compute the fold, we can just compute the result using the old value and new
4587-- value. However, we may need the buffer once in a while, for example for
4588-- string search we usually compute the hash incrementally but when the hash
4589-- matches the hash of the pattern we need to compare the whole string.
4591-- XXX we should be able to implement sequence based splitting combinators
4592-- using this combinator.
4595-- | Buffer n elements of the input in a ring buffer. When t new elements are
4596-- collected, slide the window to remove the same number of oldest elements,
4597-- insert the new elements, and apply an incremental fold on the sliding
4598-- window, supplying the outgoing elements, the new ring buffer as arguments.
4600 :: (IsStream t, Monad m, Ord a, Storable a)
4601 => Int -- window size
4602 -> Int -- window slide
4603 -> Fold m (Ring a, Array a) b
4606slidingChunkBuffer = undefined
4608-- Buffer n seconds worth of stream elements of the input in a radix tree.
4609-- Every t seconds, remove the items that are older than n seconds, and apply
4610-- an incremental fold on the sliding window, supplying the outgoing elements,
4611-- and the new radix tree buffer as arguments.
4613 :: (IsStream t, Monad m, Ord a, Storable a)
4614 => Int -- window size
4616 -> Fold m (RTree a, Array a) b
4619slidingSessionBuffer = undefined
4622------------------------------------------------------------------------------
4623-- Keyed Session Windows
4624------------------------------------------------------------------------------
4627-- | Keyed variable size space windows. Close the window if we do not receive a
4628-- window event in the next "spaceout" elements.
4629{-# INLINABLE classifyChunksBy #-}
4631 :: (IsStream t, MonadAsync m, Ord k)
4632 => Int -- ^ window spaceout (spread)
4633 -> Bool -- ^ reset the spaceout when a chunk window element is received
4634 -> Fold m a b -- ^ Fold to be applied to chunk window elements
4635 -> t m (k, a, Bool) -- ^ chunk key, data, last element
4637classifyChunksBy spanout reset (Fold step initial extract) str = undefined
4639-- | Like 'classifyChunksOf' but the chunk size is reset if an element is
4640-- received within the chunk size window. The chunk gets closed only if no
4641-- element is received within the chunk window.
4643{-# INLINABLE classifyKeepAliveChunks #-}
4644classifyKeepAliveChunks
4645 :: (IsStream t, MonadAsync m, Ord k)
4646 => Int -- ^ window spaceout (spread)
4647 -> Fold m a b -- ^ Fold to be applied to chunk window elements
4648 -> t m (k, a, Bool) -- ^ chunk key, data, last element
4650classifyKeepAliveChunks spanout = classifyChunksBy spanout True
4653data SessionState t m k a b = SessionState
4654 { sessionCurTime :: !AbsTime -- ^ time since last event
4655 , sessionEventTime :: !AbsTime -- ^ time as per last event
4656 , sessionCount :: !Int -- ^ total number sessions in progress
4657 , sessionTimerHeap :: H.Heap (H.Entry AbsTime k) -- ^ heap for timeouts
4658 , sessionKeyValueMap :: Map.Map k a -- ^ Stored sessions for keys
4659 , sessionOutputStream :: t (m :: Type -> Type) (k, b) -- ^ Completed sessions
4664-- | @classifySessionsBy tick timeout idle pred f stream@ groups timestamped
4665-- events in an input event stream into sessions based on a session key. Each
4666-- element in the stream is an event consisting of a triple @(session key,
4667-- sesssion data, timestamp)@. @session key@ is a key that uniquely identifies
4668-- the session. All the events belonging to a session are folded using the
4669-- fold @f@ until the fold returns a 'Left' result or a timeout has occurred.
4670-- The session key and the result of the fold are emitted in the output stream
4671-- when the session is purged.
4673-- When @idle@ is 'False', @timeout@ is the maximum lifetime of a session in
4674-- seconds, measured from the @timestamp@ of the first event in that session.
4675-- When @idle@ is 'True' then the timeout is an idle timeout, it is reset after
4676-- every event received in the session.
4678-- @timestamp@ in an event characterizes the time when the input event was
4679-- generated, this is an absolute time measured from some @Epoch@. The notion
4680-- of current time is maintained by a monotonic event time clock using the
4681-- timestamps seen in the input stream. The latest timestamp seen till now is
4682-- used as the base for the current time. When no new events are seen, a timer
4683-- is started with a tick duration specified by @tick@. This timer is used to
4684-- detect session timeouts in the absence of new events.
4686-- The predicate @pred@ is invoked with the current session count, if it
4687-- returns 'True' a session is ejected from the session cache before inserting
4688-- a new session. This could be useful to alert or eject sessions when the
4689-- number of sessions becomes too high.
4694-- XXX Perhaps we should use an "Event a" type to represent timestamped data.
4695{-# INLINABLE classifySessionsBy #-}
4697 :: (IsStream t, MonadAsync m, Ord k)
4698 => Double -- ^ timer tick in seconds
4699 -> Double -- ^ session timeout in seconds
4700 -> Bool -- ^ reset the timeout when an event is received
4701 -> (Int -> m Bool) -- ^ predicate to eject sessions based on session count
4702 -> Fold m a (Either b b) -- ^ Fold to be applied to session events
4703 -> t m (k, a, AbsTime) -- ^ session key, data, timestamp
4704 -> t m (k, b) -- ^ session key, fold result
4705classifySessionsBy tick tmout reset ejectPred
4706 (Fold step initial extract) str =
4707 concatMap sessionOutputStream $
4708 scanlMAfter' sstep (return szero) flush stream
4712 timeoutMs = toRelTime (round (tmout * 1000) :: MilliSecond64)
4713 tickMs = toRelTime (round (tick * 1000) :: MilliSecond64)
4714 szero = SessionState
4715 { sessionCurTime = toAbsTime (0 :: MilliSecond64)
4716 , sessionEventTime = toAbsTime (0 :: MilliSecond64)
4718 , sessionTimerHeap = H.empty
4719 , sessionKeyValueMap = Map.empty
4720 , sessionOutputStream = K.nil
4723 -- We can eject sessions based on the current session count to limit
4724 -- memory consumption. There are two possible strategies:
4726 -- 1) Eject old sessions or sessions beyond a certain/lower timeout
4727 -- threshold even before timeout, effectively reduce the timeout.
4728 -- 2) Drop creation of new sessions but keep accepting new events for the
4731 -- We use the first strategy as of now.
4733 -- Got a new stream input element
4734 sstep session@SessionState{..} (Just (key, value, timestamp)) = do
4735 -- XXX we should use a heap in pinned memory to scale it to a large
4738 -- To detect session inactivity we keep a timestamp of the latest event
4739 -- in the Map along with the fold result. When we purge the session
4740 -- from the heap we match the timestamp in the heap with the timestamp
4741 -- in the Map, if the latest timestamp is newer and has not expired we
4742 -- reinsert the key in the heap.
4744 -- XXX if the key is an Int, we can also use an IntMap for slightly
4745 -- better performance.
4747 let curTime = max sessionEventTime timestamp
4751 Just (Tuple' _ acc) -> return acc
4752 new <- step old value
4753 return $ Tuple' timestamp new
4754 mOld = Map.lookup key sessionKeyValueMap
4756 acc@(Tuple' _ fres) <- accumulate mOld
4760 -- deleting a key from the heap is expensive, so we never
4761 -- delete a key from heap, we just purge it from the Map and it
4762 -- gets purged from the heap on timeout. We just need an extra
4763 -- lookup in the Map when the key is purged from the heap, that
4764 -- should not be expensive.
4766 let (mp, cnt) = case mOld of
4767 Nothing -> (sessionKeyValueMap, sessionCount)
4768 Just _ -> (Map.delete key sessionKeyValueMap
4771 { sessionCurTime = curTime
4772 , sessionEventTime = curTime
4773 , sessionCount = cnt
4774 , sessionKeyValueMap = mp
4775 , sessionOutputStream = yield (key, x)
4778 (hp1, mp1, out1, cnt1) <- do
4779 let vars = (sessionTimerHeap, sessionKeyValueMap,
4780 K.nil, sessionCount)
4782 -- inserting new entry
4784 -- Eject a session from heap and map is needed
4785 eject <- ejectPred sessionCount
4786 (hp, mp, out, cnt) <-
4791 -- Insert the new session in heap
4792 let expiry = addToAbsTime timestamp timeoutMs
4793 hp' = H.insert (Entry expiry key) hp
4794 in return (hp', mp, out, cnt + 1)
4795 -- updating old entry
4796 Just _ -> return vars
4798 let mp2 = Map.insert key acc mp1
4799 return $ SessionState
4800 { sessionCurTime = curTime
4801 , sessionEventTime = curTime
4802 , sessionCount = cnt1
4803 , sessionTimerHeap = hp1
4804 , sessionKeyValueMap = mp2
4805 , sessionOutputStream = out1
4808 -- Got a timer tick event
4809 sstep sessionState@SessionState{..} Nothing =
4810 let curTime = addToAbsTime sessionCurTime tickMs
4811 in ejectExpired sessionState curTime
4813 flush session@SessionState{..} = do
4814 (hp', mp', out, count) <-
4817 , sessionKeyValueMap
4822 { sessionCount = count
4823 , sessionTimerHeap = hp'
4824 , sessionKeyValueMap = mp'
4825 , sessionOutputStream = out
4833 -- delete from map and output the fold accumulator
4834 ejectEntry hp mp out cnt acc key = do
4836 let out1 = (key, fromEither sess) `K.cons` out
4837 let mp1 = Map.delete key mp
4838 return (hp, mp1, out1, cnt - 1)
4840 ejectAll (hp, mp, out, !cnt) = do
4841 let hres = H.uncons hp
4843 Just (Entry _ key, hp1) -> do
4844 r <- case Map.lookup key mp of
4845 Nothing -> return (hp1, mp, out, cnt)
4846 Just (Tuple' _ acc) -> ejectEntry hp1 mp out cnt acc key
4849 assert (Map.null mp) (return ())
4850 return (hp, mp, out, cnt)
4852 ejectOne (hp, mp, out, !cnt) = do
4853 let hres = H.uncons hp
4855 Just (Entry expiry key, hp1) ->
4856 case Map.lookup key mp of
4857 Nothing -> ejectOne (hp1, mp, out, cnt)
4858 Just (Tuple' latestTS acc) -> do
4859 let expiry1 = addToAbsTime latestTS timeoutMs
4860 if not reset || expiry1 <= expiry
4861 then ejectEntry hp1 mp out cnt acc key
4863 -- reset the session timeout and continue
4864 let hp2 = H.insert (Entry expiry1 key) hp1
4865 in ejectOne (hp2, mp, out, cnt)
4867 assert (Map.null mp) (return ())
4868 return (hp, mp, out, cnt)
4870 ejectExpired session@SessionState{..} curTime = do
4871 (hp', mp', out, count) <-
4872 ejectLoop sessionTimerHeap sessionKeyValueMap K.nil sessionCount
4874 { sessionCurTime = curTime
4875 , sessionCount = count
4876 , sessionTimerHeap = hp'
4877 , sessionKeyValueMap = mp'
4878 , sessionOutputStream = out
4883 ejectLoop hp mp out !cnt = do
4884 let hres = H.uncons hp
4886 Just (Entry expiry key, hp1) -> do
4888 if curTime >= expiry
4889 then return (True, False)
4895 case Map.lookup key mp of
4896 Nothing -> ejectLoop hp1 mp out cnt
4897 Just (Tuple' latestTS acc) -> do
4898 let expiry1 = addToAbsTime latestTS timeoutMs
4899 if expiry1 <= curTime || not reset || force
4901 (hp2,mp1,out1,cnt1) <-
4902 ejectEntry hp1 mp out cnt acc key
4903 ejectLoop hp2 mp1 out1 cnt1
4905 -- reset the session timeout and continue
4906 let hp2 = H.insert (Entry expiry1 key) hp1
4907 in ejectLoop hp2 mp out cnt
4908 else return (hp, mp, out, cnt)
4910 assert (Map.null mp) (return ())
4911 return (hp, mp, out, cnt)
4913 -- merge timer events in the stream
4914 stream = Serial.map Just str `Par.parallelFst` repeatM timer
4916 liftIO $ threadDelay (round $ tick * 1000000)
4919-- | Like 'classifySessionsOf' but the session is kept alive if an event is
4920-- received within the session window. The session times out and gets closed
4921-- only if no event is received within the specified session window size.
4923-- If the ejection predicate returns 'True', the session that was idle for
4924-- the longest time is ejected before inserting a new session.
4927-- classifyKeepAliveSessions timeout pred = classifySessionsBy 1 timeout True pred
4932{-# INLINABLE classifyKeepAliveSessions #-}
4933classifyKeepAliveSessions
4934 :: (IsStream t, MonadAsync m, Ord k)
4935 => Double -- ^ session inactive timeout
4936 -> (Int -> m Bool) -- ^ predicate to eject sessions on session count
4937 -> Fold m a (Either b b) -- ^ Fold to be applied to session payload data
4938 -> t m (k, a, AbsTime) -- ^ session key, data, timestamp
4940classifyKeepAliveSessions tmout =
4941 classifySessionsBy 1 tmout True
4943------------------------------------------------------------------------------
4944-- Keyed tumbling windows
4945------------------------------------------------------------------------------
4947-- Tumbling windows is a special case of sliding windows where the window slide
4948-- is the same as the window size. Or it can be a special case of session
4949-- windows where the reset flag is set to False.
4951-- XXX instead of using the early termination flag in the stream, we can use an
4952-- early terminating fold instead.
4955-- | Split the stream into fixed size chunks of specified size. Within each
4956-- such chunk fold the elements in buckets identified by the keys. A particular
4957-- bucket fold can be terminated early if a closing flag is encountered in an
4958-- element for that key.
4961{-# INLINABLE classifyChunksOf #-}
4963 :: (IsStream t, MonadAsync m, Ord k)
4964 => Int -- ^ window size
4965 -> Fold m a b -- ^ Fold to be applied to window events
4966 -> t m (k, a, Bool) -- ^ window key, data, close event
4968classifyChunksOf wsize = classifyChunksBy wsize False
4971-- | Split the stream into fixed size time windows of specified interval in
4972-- seconds. Within each such window, fold the elements in sessions identified
4973-- by the session keys. The fold result is emitted in the output stream if the
4974-- fold returns a 'Left' result or if the time window ends.
4976-- Session @timestamp@ in the input stream is an absolute time from some epoch,
4977-- characterizing the time when the input element was generated. To detect
4978-- session window end, a monotonic event time clock is maintained synced with
4979-- the timestamps with a clock resolution of 1 second.
4981-- If the ejection predicate returns 'True', the session with the longest
4982-- lifetime is ejected before inserting a new session.
4985-- classifySessionsOf interval pred = classifySessionsBy 1 interval False pred
4990-- $ S.classifySessionsOf 3 (const (return False)) (fmap Right FL.toList)
4991-- $ S.map (\(ts,(k,a)) -> (k, a, ts))
4994-- $ (,) <$> S.fromList [1,2,3] <*> S.fromList [1,2,3]
4999{-# INLINABLE classifySessionsOf #-}
5001 :: (IsStream t, MonadAsync m, Ord k)
5002 => Double -- ^ time window size
5003 -> (Int -> m Bool) -- ^ predicate to eject sessions on session count
5004 -> Fold m a (Either b b) -- ^ Fold to be applied to session events
5005 -> t m (k, a, AbsTime) -- ^ session key, data, timestamp
5007classifySessionsOf interval =
5008 classifySessionsBy 1 interval False
5010------------------------------------------------------------------------------
5012------------------------------------------------------------------------------
5014-- | Run a side effect before the stream yields its first element.
5016-- > before action xs = 'nilM' action <> xs
5019{-# INLINE before #-}
5020before :: (IsStream t, Monad m) => m b -> t m a -> t m a
5021before action xs = D.fromStreamD $ D.before action $ D.toStreamD xs
5023-- | Run a side effect at the end of the stream. The side effect won't run if
5024-- the stream is garbage collected before it reached the end.
5026-- > after_ action xs = xs <> 'nilM' action
5028-- This has slightly better performance than 'after'.
5032{-# INLINE after_ #-}
5033after_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
5034after_ action xs = D.fromStreamD $ D.after_ action $ D.toStreamD xs
5036-- | Run a side effect at the end of the stream or if it is garbage collected
5037-- even before reaching the end.
5042after :: (IsStream t, MonadIO m, MonadBaseControl IO m)
5043 => m b -> t m a -> t m a
5044after action xs = D.fromStreamD $ D.after action $ D.toStreamD xs
5046-- | Run a side effect whenever the stream aborts due to an exception.
5049{-# INLINE onException #-}
5050onException :: (IsStream t, MonadCatch m) => m b -> t m a -> t m a
5051onException action xs = D.fromStreamD $ D.onException action $ D.toStreamD xs
5053-- | Run a side effect at the end of the stream or if it aborts due to an
5054-- exception before it could reach the end. The side effect is not run if the
5055-- stream is garbage collected before reaching the end.
5057-- This has slightly better performance than 'finally'.
5061{-# INLINE finally_ #-}
5062finally_ :: (IsStream t, MonadCatch m) => m b -> t m a -> t m a
5063finally_ action xs = D.fromStreamD $ D.finally_ action $ D.toStreamD xs
5065-- | Run a side effect at the end of the stream, or if it aborts due to an
5066-- exception or if it is garbage collected before it could reach the end.
5070{-# INLINE finally #-}
5071finally :: (IsStream t, MonadAsync m, MonadCatch m) => m b -> t m a -> t m a
5072finally action xs = D.fromStreamD $ D.finally action $ D.toStreamD xs
5074-- | Run the first action before the stream starts and remember its output,
5075-- generate a stream using the output, run the second action using the
5076-- remembered value as an argument whenever the stream ends normally or due to
5077-- an exception. The second action won't run if the stream is garbage collected
5078-- before it could reach the end.
5080-- This has slightly better performance than 'bracket'.
5084{-# INLINE bracket_ #-}
5085bracket_ :: (IsStream t, MonadCatch m)
5086 => m b -> (b -> m c) -> (b -> t m a) -> t m a
5087bracket_ bef aft bet = D.fromStreamD $
5088 D.bracket_ bef aft (toStreamD . bet)
5090-- | Run the first action before the stream starts and remember its output,
5091-- generate a stream using the output, run the second action using the
5092-- remembered value as an argument whenever the stream ends normally, due to
5093-- an exception or if it is garbage collected after a partial lazy evaluation.
5097{-# INLINE bracket #-}
5098bracket :: (IsStream t, MonadAsync m, MonadCatch m)
5099 => m b -> (b -> m c) -> (b -> t m a) -> t m a
5100bracket bef aft bet = D.fromStreamD $
5101 D.bracket bef aft (toStreamD . bet)
5103-- | When evaluating a stream if an exception occurs, stream evaluation aborts
5104-- and the specified exception handler is run with the exception as argument.
5107{-# INLINE handle #-}
5108handle :: (IsStream t, MonadCatch m, Exception e)
5109 => (e -> t m a) -> t m a -> t m a
5111 D.fromStreamD $ D.handle (D.toStreamD . handler) $ D.toStreamD xs
5113-- Keep concating either streams as long as rights are generated, stop as soon
5114-- as a left is generated and concat the left stream.
5116-- See also: 'handle'
5122 :: -- (IsStream t, MonadAsync m) =>
5123 (forall x. t m x -> t m x -> t m x)
5124 -> (a -> t m (Either (t m b) b))
5127concatMapEitherWith = undefined
5130------------------------------------------------------------------------------
5131-- Generalize the underlying monad
5132------------------------------------------------------------------------------
5134-- | Transform the inner monad of a stream using a natural transformation.
5139hoist :: (Monad m, Monad n)
5140 => (forall x. m x -> n x) -> SerialT m a -> SerialT n a
5141hoist f xs = fromStreamS $ S.hoist f (toStreamS xs)
5143-- | Generalize the inner monad of the stream from 'Identity' to any monad.
5147{-# INLINE generally #-}
5148generally :: (IsStream t, Monad m) => t Identity a -> t m a
5149generally xs = fromStreamS $ S.hoist (return . runIdentity) (toStreamS xs)
5151------------------------------------------------------------------------------
5152-- Add and remove a monad transformer
5153------------------------------------------------------------------------------
5155-- | Lift the inner monad @m@ of a stream @t m a@ to @tr m@ using the monad
5160{-# INLINE liftInner #-}
5161liftInner :: (Monad m, IsStream t, MonadTrans tr, Monad (tr m))
5162 => t m a -> t (tr m) a
5163liftInner xs = fromStreamD $ D.liftInner (toStreamD xs)
5165------------------------------------------------------------------------------
5166-- Sharing read only state in a stream
5167------------------------------------------------------------------------------
5169-- | Evaluate the inner monad of a stream as 'ReaderT'.
5173{-# INLINE runReaderT #-}
5174runReaderT :: (IsStream t, Monad m) => m s -> t (ReaderT s m) a -> t m a
5175runReaderT s xs = fromStreamD $ D.runReaderT s (toStreamD xs)
5177-- | Run a stream transformation using a given environment.
5179-- See also: 'Serial.map'
5183{-# INLINE usingReaderT #-}
5185 :: (Monad m, IsStream t)
5187 -> (t (ReaderT r m) a -> t (ReaderT r m) a)
5190usingReaderT r f xs = runReaderT r $ f $ liftInner xs
5192------------------------------------------------------------------------------
5193-- Sharing read write state in a stream
5194------------------------------------------------------------------------------
5196-- | Evaluate the inner monad of a stream as 'StateT'.
5198-- This is supported only for 'SerialT' as concurrent state updation may not be
5203{-# INLINE evalStateT #-}
5204evalStateT :: Monad m => m s -> SerialT (StateT s m) a -> SerialT m a
5205evalStateT s xs = fromStreamD $ D.evalStateT s (toStreamD xs)
5207-- | Run a stateful (StateT) stream transformation using a given state.
5209-- This is supported only for 'SerialT' as concurrent state updation may not be
5212-- See also: 'scanl''
5216{-# INLINE usingStateT #-}
5220 -> (SerialT (StateT s m) a -> SerialT (StateT s m) a)
5223usingStateT s f xs = evalStateT s $ f $ liftInner xs
5225-- | Evaluate the inner monad of a stream as 'StateT' and emit the resulting
5226-- state and value pair after each step.
5228-- This is supported only for 'SerialT' as concurrent state updation may not be
5233{-# INLINE runStateT #-}
5234runStateT :: Monad m => m s -> SerialT (StateT s m) a -> SerialT m (s, a)
5235runStateT 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