on e49a37d help sign in
5235 lines 167 kB history raw
1{-# OPTIONS_GHC -Wno-orphans #-}
3#include "inline.hs"
5-- |
6-- Module : Streamly.Internal.Data.Stream.IsStream
7-- Copyright : (c) 2017 Composewell Technologies
8--
9-- License : BSD3
10-- Maintainer : streamly@composewell.com
11-- Stability : experimental
12-- Portability : GHC
13--
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
21 (
22 -- * Stream Types
23 -- ** Serial Streams
24 SerialT
25 , Serial
26 , WSerialT
27 , WSerial
29 -- ** Speculative Streams
30 , AheadT
31 , Ahead
33 -- ** Asynchronous Streams
34 , AsyncT
35 , Async
36 , WAsyncT
37 , WAsync
38 , ParallelT
39 , Parallel
40 , mkAsync
42 -- ** Zipping Streams
43 , ZipSerialM
44 , ZipSerial
45 , ZipAsyncM
46 , ZipAsync
48 -- * Stream Type Adapters
49 , IsStream ()
51 , serially
52 , wSerially
53 , asyncly
54 , aheadly
55 , wAsyncly
56 , parallely
57 , zipSerially
58 , zipAsyncly
59 , adapt
61 -- * Type Synonyms
62 , MonadAsync
64 -- * Construction
65 -- ** Primitives
66 , K.nil
67 , K.nilM
68 , K.cons
69 , (K..:)
71 , consM
72 , (|:)
74 -- ** From Values
75 , yield
76 , yieldM
77 , repeat
78 , repeatM
79 , replicate
80 , replicateM
82 -- ** Enumeration
83 , Enumerable (..)
84 , enumerate
85 , enumerateTo
87 -- ** Time Enumeration
88 , times
89 , absTimes
90 , relTimes
91 , durations
92 , ticks
93 , timeout
94 , currentTime
96 -- ** From Generators
97 , unfoldr
98 , unfoldrM
99 , unfold
100 , unfold0
101 , fromIndices
102 , fromIndicesM
104 -- ** Iteration
105 , iterate
106 , iterateM
108 -- ** Cyclic Elements
109 , K.mfix
111 -- ** From Containers
112 , P.fromList
113 , fromListM
114 , K.fromFoldable
115 , fromFoldableM
116 , fromPrimIORef
117 , fromCallback
119 -- * Elimination
121 -- ** Deconstruction
122 , uncons
123 , tail
124 , init
126 -- ** Folding
127 -- ** Right Folds
128 , foldrM
129 , foldrS
130 , foldrT
131 , foldr
133 -- ** Left Folds
134 , foldl'
135 , foldl1'
136 , foldlM'
138 -- ** Composable Left Folds
139 , fold
140 , parse
141 , parseK
142 , parseD
144 -- ** Concurrent Folds
145 , foldAsync
146 , (|$.)
147 , (|&.)
149 -- ** Full Folds
151 -- -- ** To Summary (Full Folds)
152 , drain
153 , last
154 , length
155 , sum
156 , product
157 , mconcat
159 -- -- ** To Summary (Maybe) (Full Folds)
160 , maximumBy
161 , maximum
162 , minimumBy
163 , minimum
164 , the
166 -- ** Lazy Folds
167 -- -- ** To Containers (Full Folds)
168 , toList
169 , toListRev
170 , toPure
171 , toPureRev
173 -- ** Composable Left Folds
175 , toStream -- XXX rename to write?
176 , toStreamRev -- XXX rename to writeRev?
178 -- ** Partial Folds
180 -- -- ** To Elements (Partial Folds)
181 , drainN
182 , drainWhile
184 -- -- | Folds that extract selected elements of a stream or their properties.
185 , (!!)
186 , head
187 , headElse
188 , findM
189 , find
190 , lookup
191 , findIndex
192 , elemIndex
194 -- -- ** To Boolean (Partial Folds)
195 , null
196 , elem
197 , notElem
198 , all
199 , any
200 , and
201 , or
203 -- ** Multi-Stream folds
204 -- Full equivalence
205 , eqBy
206 , cmpBy
208 -- finding subsequences
209 , isPrefixOf
210 , isSuffixOf
211 , isInfixOf
212 , isSubsequenceOf
214 -- trimming sequences
215 , stripPrefix
216 , stripSuffix
217 -- , stripInfix
218 , dropPrefix
219 , dropInfix
220 , dropSuffix
222 -- * Transformation
223 , transform
225 -- ** Mapping
226 , Serial.map
227 , sequence
228 , mapM
229 , smapM
230 -- $smapM_Notes
232 -- ** Special Maps
233 , mapM_
234 , trace
235 , trace_
236 , tap
237 , tapOffsetEvery
238 , tapAsync
239 , tapRate
240 , pollCounts
242 -- ** Scanning
243 -- ** Left scans
244 , scanl'
245 , scanlM'
246 , scanlMAfter'
247 , postscanl'
248 , postscanlM'
249 , prescanl'
250 , prescanlM'
251 , scanl1'
252 , scanl1M'
254 -- ** Scan Using Fold
255 , scan
256 , postscan
258 -- XXX Once we have pipes the contravariant transformations can be
259 -- represented by attaching pipes before a transformation.
260 --
261 -- , lscanl'
262 -- , lscanlM'
263 -- , lscanl1'
264 -- , lscanl1M'
265 --
266 -- , lpostscanl'
267 -- , lpostscanlM'
268 -- , lprescanl'
269 -- , lprescanlM'
271 -- ** Concurrent Transformation
272 , D.mkParallel
273 -- Par.mkParallel
274 , applyAsync
275 , (|$)
276 , (|&)
278 -- ** Filtering
280 , filter
281 , filterM
283 -- ** Deleting Elements
284 , deleteBy
285 , uniq
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
292 , insertBy
293 , intersperseM
294 , intersperseM_
295 , intersperse
296 , intersperseSuffix
297 , intersperseSuffix_
298 , interspersePrefix_
299 , intersperseSuffixBySpan
300 -- , intersperseBySpan
301 -- , intersperseByIndices -- using an index function/stream
303 -- time domain intersperse
304 -- , intersperseByTime
305 -- , intersperseByEvent
306 , interjectSuffix
307 , delay
308 , delayPost
309 , delayPre
311 -- ** Indexing
312 , indexed
313 , indexedR
314 , timestamped
315 , timeIndexed
316 -- , timestampedR -- timer
318 -- ** Reordering
319 , reverse
320 , reverse'
322 -- ** Parsing
323 , parseMany
324 , parseManyD
325 , parseManyTill
326 , parseIterate
328 -- ** Trimming
329 , take
330 -- , takeGE
331 -- , takeBetween
332 , takeByTime
333 -- , takeEnd
334 , takeWhile
335 , takeWhileM
336 -- , takeWhileEnd
337 , drop
338 , dropByTime
339 -- , dropEnd
340 , dropWhile
341 , dropWhileM
342 -- , dropWhileEnd
343 -- , dropAround
345 -- ** Breaking
347 -- Nary
348 , chunksOf
349 , chunksOf2
350 , arraysOf
351 , intervalsOf
353 -- ** Searching
354 -- -- *** Searching Elements
355 , findIndices
356 , elemIndices
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.
367 -- ** Splitting
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
373 , splitOn
374 , splitOnSuffix
375 -- , splitOnPrefix
377 -- , splitBy
378 , splitWithSuffix
379 -- , splitByPrefix
380 , wordsBy -- stripAndCompactBy
382 -- -- *** Splitting By Sequences
383 , splitOnSeq
384 , splitOnSuffixSeq
385 -- , splitOnPrefixSeq
387 -- Keeping the delimiters
388 , splitBySeq
389 , splitWithSuffixSeq
390 -- , splitByPrefixSeq
391 -- , wordsBySeq
393 -- Splitting using multiple sequence separators
394 -- , splitOnAnySeq
395 -- , splitOnAnySuffixSeq
396 -- , splitOnAnyPrefixSeq
398 -- -- *** Splitting By Streams
399 -- -- | Splitting a stream using another stream as separator.
401 -- Nested splitting
402 , splitInnerBy
403 , splitInnerBySuffix
405 -- ** Grouping
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
409 -- output stream.
411 -- , groupScan
413 , groups
414 , groupsBy
415 , groupsByRolling
417 -- ** Group map
418 , rollingMapM
419 , rollingMap
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.
428 --
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
436 , classifySessionsBy
437 , classifySessionsOf
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
446 {-
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
452 -}
453 -- ** Sliding Window Buffers
454 -- , slidingChunkBuffer
455 -- , slidingSessionBuffer
457 -- * Combining Streams
459 -- ** Appending
460 , serial
461 , append
463 -- ** Interleaving
464 , interleave
465 , interleaveMin
466 , interleaveSuffix
467 , interleaveInfix
469 , wSerial
470 , Serial.wSerialFst
471 , Serial.wSerialMin
473 -- ** Scheduling
474 , ahead
475 , async
476 , wAsync
477 , roundrobin
479 -- ** Parallel
480 , parallel
481 , Par.parallelFst
482 , Par.parallelMin
484 -- ** Merging
485 -- , merge
486 , mergeBy
487 , mergeByM
488 , mergeAsyncBy
489 , mergeAsyncByM
491 -- ** Zipping
492 , Z.zipWith
493 , Z.zipWithM
494 , Z.zipAsyncWith
495 , Z.zipAsyncWithM
497 -- ** Flattening a Container of Streams
498 , concatFoldableWith
499 , concatMapFoldableWith
500 , concatForFoldableWith
502 -- ** Flattening a Stream of Streams
503 , concat
504 , concatM
505 , concatMap
506 , concatMapM
507 , concatMapWith
508 , concatSmapMWith
509 -- , bindWith
511 -- ** Flattening Using Unfolds
512 , concatUnfold
513 , concatUnfoldInterleave
514 , concatUnfoldRoundrobin
516 -- ** Flattening a Tree of Streams
517 , iterateMapWith
519 -- ** Flattening a Graph of Streams
520 , iterateSmapMWith
522 -- ** Inserting Streams in Streams
523 , gintercalate
524 , gintercalateSuffix
525 , intercalate
526 , intercalateSuffix
527 , interpose
528 , interposeSuffix
529 -- , interposeBy
531 -- * Exceptions
532 , before
533 , after_
534 , after
535 , bracket_
536 , bracket
537 , onException
538 , finally_
539 , finally
540 , handle
542 -- * Generalize Inner Monad
543 , hoist
544 , generally
546 -- * Transform Inner Monad
547 , liftInner
548 , usingReaderT
549 , runReaderT
550 , evalStateT
551 , usingStateT
552 , runStateT
554 -- * Maybe Streams
555 , catMaybes
556 , mapMaybe
557 , mapMaybeM
559 -- * Either Streams
560 , lefts
561 , rights
562 , iterateMapLeftsWith
564 -- * Concurrency Control
565 , maxThreads
566 , maxBuffer
568 -- * Rate Limiting
569 , Rate (..)
570 , rate
571 , avgRate
572 , minRate
573 , maxRate
574 , constRate
576 -- * Diagnostics
577 , inspectMode
579 -- * Deprecated
580 , K.once
581 , each
582 , scanx
583 , foldx
584 , foldxM
585 , foldr1
586 , runStream
587 , runN
588 , runWhile
589 , fromHandle
590 , toHandle
591 )
592where
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
621 , wAsyncly)
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
634 , wSerially)
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
661#else
662import qualified Streamly.Internal.Data.Stream.StreamD as S
663#endif
665import Prelude hiding
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------------------------------------------------------------------------------
674-- Deconstruction
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.
680--
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.
686--
687-- @since 0.1.0
688{-# INLINE uncons #-}
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------------------------------------------------------------------------------
696-- |
697-- @
698-- unfoldr step s =
699-- case step s of
700-- Nothing -> 'K.nil'
701-- Just (a, b) -> a \`cons` unfoldr step b
702-- @
703--
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.
707-- For example,
708--
709-- @
710-- let f b =
711-- if b > 3
712-- then Nothing
713-- else Just (b, b + 1)
714-- in toList $ unfoldr f 0
715-- @
716-- @
717-- [0,1,2,3]
718-- @
719--
720-- @since 0.1.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
730-- example,
731--
732-- @
733-- let f b =
734-- if b > 3
735-- then return Nothing
736-- else print b >> return (Just (b, b + 1))
737-- in drain $ unfoldrM f 0
738-- @
739-- @
740-- 0
741-- 1
742-- 2
743-- 3
744-- @
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
748-- previous step.
749--
750-- @
751-- (asyncly $ S.unfoldrM (\\n -> liftIO (threadDelay 1000000) >> return (Just (n, n + 1))) 0)
752-- & S.foldlM' (\\_ a -> threadDelay 1000000 >> print a) ()
753-- @
754--
755-- /Concurrent/
756--
757-- /Since: 0.1.0/
758{-# INLINE_EARLY unfoldrM #-}
759unfoldrM :: (IsStream t, MonadAsync m) => (b -> m (Maybe (a, b))) -> b -> t m a
760unfoldrM = K.unfoldrM
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.
778--
779-- >>> unfold (UF.replicateM 10) (putStrLn "hello")
780--
781-- /Since: 0.7.0/
782{-# INLINE unfold #-}
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.
787--
788-- /Internal/
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.
798--
799-- |
800-- @
801-- yield a = a \`cons` nil
802-- @
803--
804-- Create a singleton stream from a pure value.
805--
806-- The following holds in monadic streams, but not in Zip streams:
807--
808-- @
809-- yield = pure
810-- yield = yieldM . pure
811-- @
812--
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.
817--
818-- @since 0.4.0
819{-# INLINE yield #-}
820yield :: IsStream t => a -> t m a
821yield = K.yield
823-- |
824-- @
825-- yieldM m = m \`consM` nil
826-- @
827--
828-- Create a singleton stream from a monadic action.
829--
830-- @
831-- > toList $ yieldM getLine
832-- hello
833-- ["hello"]
834-- @
835--
836-- @since 0.4.0
837{-# INLINE yieldM #-}
838yieldM :: (Monad m, IsStream t) => m a -> t m a
839yieldM = K.yieldM
841-- |
842-- @
843-- fromIndices f = let g i = f i \`cons` g (i + 1) in g 0
844-- @
845--
846-- Generate an infinite stream, whose values are the output of a function @f@
847-- applied on the corresponding index. Index starts at 0.
848--
849-- @
850-- > S.toList $ S.take 5 $ S.fromIndices id
851-- [0,1,2,3,4]
852-- @
853--
854-- @since 0.6.0
855{-# INLINE fromIndices #-}
856fromIndices :: (IsStream t, Monad m) => (Int -> a) -> t m a
857fromIndices = fromStreamS . S.fromIndices
859--
860-- |
861-- @
862-- fromIndicesM f = let g i = f i \`consM` g (i + 1) in g 0
863-- @
864--
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.
867--
868-- /Concurrent/
869--
870-- @since 0.6.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
880-- |
881-- @
882-- replicateM = take n . repeatM
883-- @
884--
885-- Generate a stream by performing a monadic action @n@ times. Same as:
886--
887-- @
888-- drain $ serially $ S.replicateM 10 $ (threadDelay 1000000 >> print 1)
889-- drain $ asyncly $ S.replicateM 10 $ (threadDelay 1000000 >> print 1)
890-- @
891--
892-- /Concurrent/
893--
894-- @since 0.1.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
904-- |
905-- @
906-- replicate = take n . repeat
907-- @
908--
909-- Generate a stream of length @n@ by repeating a value @n@ times.
910--
911-- @since 0.6.0
912{-# INLINE_NORMAL replicate #-}
913replicate :: (IsStream t, Monad m) => Int -> a -> t m a
914replicate n = fromStreamS . S.replicate n
916-- |
917-- Generate an infinite stream by repeating a pure value.
918--
919-- @since 0.4.0
920{-# INLINE_NORMAL repeat #-}
921repeat :: (IsStream t, Monad m) => a -> t m a
922repeat = fromStreamS . S.repeat
924-- |
925-- @
926-- repeatM = fix . consM
927-- repeatM = cycle1 . yieldM
928-- @
929--
930-- Generate a stream by repeatedly executing a monadic action forever.
931--
932-- @
933-- drain $ serially $ S.take 10 $ S.repeatM $ (threadDelay 1000000 >> print 1)
934-- drain $ asyncly $ S.take 10 $ S.repeatM $ (threadDelay 1000000 >> print 1)
935-- @
936--
937-- /Concurrent, infinite (do not use with 'parallely')/
938--
939-- @since 0.2.0
940{-# INLINE_EARLY repeatM #-}
941repeatM :: (IsStream t, MonadAsync m) => m a -> t m a
942repeatM = K.repeatM
944{-# RULES "repeatM serial" repeatM = repeatMSerial #-}
945{-# INLINE repeatMSerial #-}
946repeatMSerial :: MonadAsync m => m a -> SerialT m a
947repeatMSerial = fromStreamS . S.repeatM
949-- |
950-- @
951-- iterate f x = x \`cons` iterate f x
952-- @
953--
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
956-- element.
957--
958-- @
959-- > S.toList $ S.take 5 $ S.iterate (+1) 1
960-- [1,2,3,4,5]
961-- @
962--
963-- @since 0.1.2
964{-# INLINE_NORMAL iterate #-}
965iterate :: (IsStream t, Monad m) => (a -> a) -> a -> t m a
966iterate step = fromStreamS . S.iterate step
968-- |
969-- @
970-- iterateM f m = m >>= \a -> return a \`consM` iterateM f (f a)
971-- @
972--
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.
976--
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.
981--
982-- @
983-- drain $ serially $ S.take 10 $ S.iterateM
984-- (\\x -> threadDelay 1000000 >> print x >> return (x + 1)) (return 0)
985--
986-- drain $ asyncly $ S.take 10 $ S.iterateM
987-- (\\x -> threadDelay 1000000 >> print x >> return (x + 1)) (return 0)
988-- @
989--
990-- /Concurrent/
991--
992-- /Since: 0.1.2/
993--
994-- /Since: 0.7.0 (signature change)/
995{-# INLINE_EARLY iterateM #-}
996iterateM :: (IsStream t, MonadAsync m) => (a -> m a) -> m a -> t m a
997iterateM = K.iterateM
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------------------------------------------------------------------------------
1005-- Conversions
1006------------------------------------------------------------------------------
1008-- |
1009-- @
1010-- fromListM = 'Prelude.foldr' 'K.consM' 'K.nil'
1011-- @
1013-- Construct a stream from a list of monadic actions. This is more efficient
1014-- than 'fromFoldableM' for serial streams.
1016-- @since 0.4.0
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 #-}
1023-- |
1024-- @
1025-- fromFoldableM = 'Prelude.foldr' 'consM' 'K.nil'
1026-- @
1028-- Construct a stream from a 'Foldable' containing monadic actions.
1030-- @
1031-- drain $ serially $ S.fromFoldableM $ replicateM 10 (threadDelay 1000000 >> print 1)
1032-- drain $ asyncly $ S.fromFoldableM $ replicateM 10 (threadDelay 1000000 >> print 1)
1033-- @
1035-- /Concurrent (do not use with 'parallely' on infinite containers)/
1037-- @since 0.3.0
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'.
1044-- @since 0.1.0
1045{-# DEPRECATED each "Please use fromFoldable instead." #-}
1046{-# INLINE each #-}
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.
1052-- @since 0.1.0
1053{-# DEPRECATED fromHandle
1054 "Please use Streamly.FileSystem.Handle module (see the changelog)" #-}
1055fromHandle :: (IsStream t, MonadIO m) => IO.Handle -> t m String
1056fromHandle h = go
1057 where
1058 go = K.mkStream $ \_ yld _ stp -> do
1059 eof <- liftIO $ IO.hIsEOF h
1060 if eof
1061 then stp
1062 else do
1063 str <- liftIO $ IO.hGetLine h
1064 yld str go
1066-- | Construct a stream by reading a 'Prim' 'IORef' repeatedly.
1068-- /Internal/
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.
1078-- /Internal/
1080{-# INLINE fromCallback #-}
1081fromCallback :: MonadAsync m => ((a -> m ()) -> m ()) -> SerialT m a
1082fromCallback setCallback = concatM $ do
1083 (callback, stream) <- D.newCallbackStream
1084 setCallback callback
1085 return stream
1087------------------------------------------------------------------------------
1088-- Time related
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.
1099-- @
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))
1104-- @
1106-- Note: This API is not safe on 32-bit machines.
1108-- /Internal/
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.
1119-- @
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))
1124-- @
1126-- Note: This API is not safe on 32-bit machines.
1128-- /Internal/
1130{-# INLINE times #-}
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
1137-- as 1 ms.
1139-- @
1140-- >>> S.mapM_ print $ S.delayPre 1 $ S.absTimesWith 0.01
1141-- @
1143-- Note: This API is not safe on 32-bit machines.
1145-- /Internal/
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
1153-- granularity.
1155-- @
1156-- >>> S.mapM_ print $ S.delayPre 1 $ S.absTimes
1157-- @
1159-- Note: This API is not safe on 32-bit machines.
1161-- /Internal/
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.
1178-- @
1179-- >>> S.mapM_ print $ S.delayPre 1 $ S.relTimesWith 0.01
1180-- > RelTime64 (NanoSecond64 0)
1181-- > RelTime64 (NanoSecond64 91139000)
1182-- > RelTime64 (NanoSecond64 204052000)
1183-- @
1185-- Note: This API is not safe on 32-bit machines.
1187-- /Internal/
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.
1197-- @
1198-- >>> S.mapM_ print $ S.delayPre 1 $ S.relTimes
1199-- @
1201-- Note: This API is not safe on 32-bit machines.
1203-- /Internal/
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.
1218-- /Unimplemented/
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.
1231-- /Unimplemented/
1233{-# INLINE ticks #-}
1234ticks :: -- (IsStream t, MonadAsync m) =>
1235 Rate -> t m ()
1236ticks = undefined
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.
1243-- /Unimplemented/
1245{-# INLINE timeout #-}
1246timeout :: -- (IsStream t, MonadAsync m) =>
1247 AbsTime -> t m ()
1248timeout = undefined
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)
1267-- > True
1269-- /Since: 0.7.0 (signature changed)/
1271-- /Since: 0.2.0 (signature changed)/
1273-- /Since: 0.1.0/
1274{-# INLINE foldrM #-}
1275foldrM :: Monad m => (a -> m b -> m b) -> m b -> SerialT m a -> m b
1276foldrM = P.foldrM
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]
1288-- > [1,2,3,4,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)
1293-- > [True]
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)
1298-- > [3,5,7]
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
1305-- /Internal/
1306{-# INLINE foldrS #-}
1307foldrS :: IsStream t => (a -> t m b -> t m b) -> t m b -> t m a -> t m b
1308foldrS = K.foldrS
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:
1314-- > foldrS = foldrT
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.
1320-- /Internal/
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
1327-- monads.
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
1334-- all its input.
1336-- @since 0.1.0
1337{-# INLINE foldr #-}
1338foldr :: Monad m => (a -> b -> b) -> b -> SerialT m a -> m b
1339foldr = P.foldr
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.
1347-- @since 0.5.0
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.
1358-- @since 0.2.0
1359{-# DEPRECATED foldx "Please use foldl' followed by fmap instead." #-}
1360{-# INLINE foldx #-}
1361foldx :: Monad m => (x -> a -> x) -> x -> (x -> b) -> SerialT m a -> m b
1362foldx = P.foldlx'
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.
1372-- @since 0.2.0
1373{-# INLINE foldl' #-}
1374foldl' :: Monad m => (b -> a -> b) -> b -> SerialT m a -> m b
1375foldl' = P.foldl'
1377-- | Strict left fold, for non-empty streams, using first element as the
1378-- starting value. Returns 'Nothing' if the stream is empty.
1380-- @since 0.5.0
1381{-# INLINE foldl1' #-}
1382foldl1' :: Monad m => (a -> a -> a) -> SerialT m a -> m (Maybe a)
1383foldl1' step m = do
1384 r <- uncons m
1385 case r of
1386 Nothing -> return Nothing
1387 Just (h, t) -> do
1388 res <- foldl' step h t
1389 return $ Just res
1391-- | Like 'foldx', but with a monadic step function.
1393-- @since 0.2.0
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
1397foldxM = P.foldlMx'
1399-- | Like 'foldl'' but with a monadic step function.
1401-- /Since: 0.2.0/
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------------------------------------------------------------------------------
1409-- Running a Fold
1410------------------------------------------------------------------------------
1412-- | Fold a stream using the supplied left fold.
1414-- >>> S.fold FL.sum (S.enumerateFromTo 1 100)
1415-- 5050
1417-- @since 0.7.0
1418{-# INLINE fold #-}
1419fold :: Monad m => Fold m a b -> SerialT m a -> m b
1420fold = P.runFold
1422------------------------------------------------------------------------------
1423-- Running a sink
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------------------------------------------------------------------------------
1434-- Running a Parser
1435------------------------------------------------------------------------------
1437-- | Parse a stream using the supplied 'Parser'.
1439-- /Internal/
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
1447parseK = parse
1449-- | Parse a stream using the supplied 'Parser'.
1451-- /Internal/
1453{-# INLINE [3] parse #-}
1454parse :: MonadThrow m => Parser m a b -> SerialT m a -> m b
1455parse = parseD . PRK.fromParserK
1457------------------------------------------------------------------------------
1458-- Specialized folds
1459------------------------------------------------------------------------------
1461-- |
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'@.
1468-- @since 0.7.0
1469{-# INLINE drain #-}
1470drain :: Monad m => SerialT m a -> m ()
1471drain = P.drain
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'@.
1477-- @since 0.2.0
1478{-# DEPRECATED runStream "Please use \"drain\" instead" #-}
1479{-# INLINE runStream #-}
1480runStream :: Monad m => SerialT m a -> m ()
1481runStream = drain
1483-- |
1484-- > drainN n = drain . take n
1486-- Run maximum up to @n@ iterations of a stream.
1488-- @since 0.7.0
1489{-# INLINE drainN #-}
1490drainN :: Monad m => Int -> SerialT m a -> m ()
1491drainN n = drain . take n
1493-- |
1494-- > runN n = runStream . take n
1496-- Run maximum up to @n@ iterations of a stream.
1498-- @since 0.6.0
1499{-# DEPRECATED runN "Please use \"drainN\" instead" #-}
1500{-# INLINE runN #-}
1501runN :: Monad m => Int -> SerialT m a -> m ()
1502runN = drainN
1504-- |
1505-- > drainWhile p = drain . takeWhile p
1507-- Run a stream as long as the predicate holds true.
1509-- @since 0.7.0
1510{-# INLINE drainWhile #-}
1511drainWhile :: Monad m => (a -> Bool) -> SerialT m a -> m ()
1512drainWhile p = drain . takeWhile p
1514-- |
1515-- > runWhile p = runStream . takeWhile p
1517-- Run a stream as long as the predicate holds true.
1519-- @since 0.6.0
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.
1527-- @since 0.1.1
1528{-# INLINE null #-}
1529null :: Monad m => SerialT m a -> m Bool
1530null = S.null . toStreamS
1532-- | Extract the first element of the stream, if any.
1534-- > head = (!! 0)
1536-- @since 0.1.0
1537{-# INLINE head #-}
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
1543-- code.
1545-- /Internal/
1546{-# INLINE headElse #-}
1547headElse :: Monad m => a -> SerialT m a -> m a
1548headElse x = D.headElse x . toStreamD
1550-- |
1551-- > tail = fmap (fmap snd) . uncons
1553-- Extract all but the first element of the stream, if any.
1555-- @since 0.1.1
1556{-# INLINE tail #-}
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.
1562-- @since 0.5.0
1563{-# INLINE init #-}
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)
1571-- @since 0.1.1
1572{-# INLINE last #-}
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.
1578-- @since 0.1.0
1579{-# INLINE elem #-}
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.
1585-- @since 0.1.0
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.
1592-- @since 0.1.0
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.
1599-- @since 0.1.0
1600{-# INLINE all #-}
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.
1606-- @since 0.1.0
1607{-# INLINE any #-}
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.
1613-- @since 0.5.0
1614{-# INLINE and #-}
1615and :: Monad m => SerialT m Bool -> m Bool
1616and = all (==True)
1618-- | Determines whether at least one element of a boolean stream is True.
1620-- @since 0.5.0
1621{-# INLINE or #-}
1622or :: Monad m => SerialT m Bool -> m Bool
1623or = any (==True)
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
1627-- point numbers.
1629-- @since 0.1.0
1630{-# INLINE sum #-}
1631sum :: (Monad m, Num a) => SerialT m a -> m a
1632sum = foldl' (+) 0
1634-- | Determine the product of all elements of a stream of numbers. Returns @1@
1635-- when the stream is empty.
1637-- @since 0.1.1
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.
1644-- /Internal/
1645{-# INLINE mconcat #-}
1646mconcat :: (Monad m, Monoid a) => SerialT m a -> m a
1647mconcat = foldr mappend mempty
1649-- |
1650-- @
1651-- minimum = 'minimumBy' compare
1652-- @
1654-- Determine the minimum element in a stream.
1656-- @since 0.1.0
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
1662-- function.
1664-- @since 0.6.0
1665{-# INLINE minimumBy #-}
1666minimumBy :: Monad m => (a -> a -> Ordering) -> SerialT m a -> m (Maybe a)
1667minimumBy cmp m = S.minimumBy cmp (toStreamS m)
1669-- |
1670-- @
1671-- maximum = 'maximumBy' compare
1672-- @
1674-- Determine the maximum element in a stream.
1676-- @since 0.1.0
1677{-# INLINE maximum #-}
1678maximum :: (Monad m, Ord a) => SerialT m a -> m (Maybe a)
1679maximum = P.maximum
1681-- | Determine the maximum element in a stream using the supplied comparison
1682-- function.
1684-- @since 0.6.0
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.
1691-- @since 0.6.0
1692{-# INLINE (!!) #-}
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)
1701-- @since 0.5.0
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)
1710-- @since 0.5.0
1711{-# INLINE find #-}
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.
1717-- @since 0.6.0
1718{-# INLINE findM #-}
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
1723-- predicate.
1725-- @since 0.5.0
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.
1732-- @since 0.5.0
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.
1740-- @since 0.5.0
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)
1749-- @since 0.5.0
1750{-# INLINE elemIndex #-}
1751elemIndex :: (Monad m, Eq a) => a -> SerialT m a -> m (Maybe Int)
1752elemIndex a = findIndex (== a)
1754------------------------------------------------------------------------------
1755-- Substreams
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.
1761-- @
1762-- > S.isPrefixOf (S.fromList "hello") (S.fromList "hello" :: SerialT IO Char)
1763-- True
1764-- @
1766-- @since 0.6.0
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.
1790-- @
1791-- > S.isSuffixOf (S.fromList "hello") (S.fromList "hello" :: SerialT IO Char)
1792-- True
1793-- @
1795-- Space: @O(n)@, buffers entire input stream and the suffix.
1797-- /Internal/
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.
1808-- @
1809-- > S.isInfixOf (S.fromList "hello") (S.fromList "hello" :: SerialT IO Char)
1810-- True
1811-- @
1813-- Space: @O(n)@ worst case where @n@ is the length of the infix.
1815-- /Internal/
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
1826 return (not r)
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.
1832-- @
1833-- > S.isSubsequenceOf (S.fromList "hlo") (S.fromList "hello" :: SerialT IO Char)
1834-- True
1835-- @
1837-- @since 0.6.0
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
1845-- stream.
1847-- Space: @O(1)@
1849-- @since 0.6.0
1850{-# INLINE stripPrefix #-}
1851stripPrefix
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
1867-- instance.
1869-- Space: @O(n)@, buffers the entire input stream as well as the suffix
1871-- /Internal/
1872{-# INLINE stripSuffix #-}
1873stripSuffix
1874 :: (Monad m, Eq a)
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.
1880-- Space: @O(1)@
1882-- /Unimplemented/ - Help wanted.
1883{-# INLINE dropPrefix #-}
1884dropPrefix ::
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 #-}
1896dropInfix ::
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 #-}
1908dropSuffix ::
1909 -- (Eq a, IsStream t, Monad m) =>
1910 t m a -> t m a -> t m a
1911dropSuffix = error "Not implemented yet!"
1913------------------------------------------------------------------------------
1914-- Map and Fold
1915------------------------------------------------------------------------------
1917-- XXX this can utilize parallel mapping if we implement it as drain . mapM
1918-- |
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.
1925-- @since 0.1.0
1926{-# INLINE mapM_ #-}
1927mapM_ :: Monad m => (a -> m b) -> SerialT m a -> m ()
1928mapM_ f m = S.mapM_ f $ toStreamS m
1930------------------------------------------------------------------------------
1931-- Conversions
1932------------------------------------------------------------------------------
1934-- |
1935-- @
1936-- toList = S.foldr (:) []
1937-- @
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.
1946-- @since 0.1.0
1947{-# INLINE toList #-}
1948toList :: Monad m => SerialT m a -> m [a]
1949toList = P.toList
1951-- |
1952-- @
1953-- toListRev = S.foldl' (flip (:)) []
1954-- @
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.
1961-- /Internal/
1962{-# INLINE toListRev #-}
1963toListRev :: Monad m => SerialT m a -> m [a]
1964toListRev = D.toListRev . toStreamD
1966-- |
1967-- @
1968-- toHandle h = S.mapM_ $ hPutStrLn h
1969-- @
1971-- Write a stream of Strings to an IO Handle.
1973-- @since 0.1.0
1974{-# DEPRECATED toHandle
1975 "Please use Streamly.FileSystem.Handle module (see the changelog)" #-}
1976toHandle :: MonadIO m => IO.Handle -> SerialT m String -> m ()
1977toHandle h = go
1978 where
1979 go m1 =
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
1986-- in other modules.
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.
1993-- /Internal/
1994{-# INLINE toStream #-}
1995toStream :: Monad m => Fold m a (SerialT Identity a)
1996toStream = Fold (\f x -> return $ f . (x `K.cons`))
1997 (return id)
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
2004-- input.
2006-- /Warning!/ working on large streams accumulated as buffers in memory could
2007-- be very inefficient, consider using "Streamly.Data.Array" instead.
2009-- /Internal/
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.
2018-- @
2019-- toPure = foldr cons nil
2020-- @
2022-- /Internal/
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.
2030-- @
2031-- toPureRev = foldl' (flip cons) nil
2032-- @
2034-- /Internal/
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------------------------------------------------------------------------------
2044infixr 0 |$
2045infixr 0 |$.
2047infixl 1 |&
2048infixl 1 |&.
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
2062-- 1 second delay.
2065-- @
2066-- drain $
2067-- S.mapM (\\x -> threadDelay 1000000 >> print x)
2068-- |$ S.repeatM (threadDelay 1000000 >> return 1)
2069-- @
2071-- /Concurrent/
2073-- /Since: 0.3.0 ("Streamly")/
2075-- @since 0.8.0
2076{-# INLINE (|$) #-}
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
2081-- | Same as '|$'.
2083-- /Internal/
2085{-# INLINE applyAsync #-}
2086applyAsync :: (IsStream t, MonadAsync m)
2087 => (t m a -> t m b) -> (t m a -> t m b)
2088applyAsync = (|$)
2090-- | Parallel reverse function application operator for streams; just like the
2091-- regular reverse function application operator '&' except that it is
2092-- concurrent.
2094-- @
2095-- drain $
2096-- S.repeatM (threadDelay 1000000 >> return 1)
2097-- |& S.mapM (\\x -> threadDelay 1000000 >> print x)
2098-- @
2100-- /Concurrent/
2102-- /Since: 0.3.0 ("Streamly")/
2104-- @since 0.8.0
2105{-# INLINE (|&) #-}
2106(|&) :: (IsStream t, MonadAsync m) => t m a -> (t m a -> t m b) -> t m b
2107x |& f = f |$ x
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
2113-- buffer.
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
2120-- stream.
2122-- @
2123-- S.foldlM' (\\_ a -> threadDelay 1000000 >> print a) ()
2124-- |$. S.repeatM (threadDelay 1000000 >> return 1)
2125-- @
2127-- /Concurrent/
2129-- /Since: 0.3.0 ("Streamly")/
2131-- @since 0.8.0
2132{-# INLINE (|$.) #-}
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
2137-- | Same as '|$.'.
2139-- /Internal/
2141{-# INLINE foldAsync #-}
2142foldAsync :: (IsStream t, MonadAsync m) => (t m a -> m b) -> (t m a -> m b)
2143foldAsync = (|$.)
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.
2148-- @
2149-- S.repeatM (threadDelay 1000000 >> return 1)
2150-- |&. S.foldlM' (\\_ a -> threadDelay 1000000 >> print a) ()
2151-- @
2153-- /Concurrent/
2155-- /Since: 0.3.0 ("Streamly")/
2157-- @since 0.8.0
2158{-# INLINE (|&.) #-}
2159(|&.) :: (IsStream t, MonadAsync m) => t m a -> (t m a -> m b) -> m b
2160x |&. f = f |$. x
2162------------------------------------------------------------------------------
2163-- General Transformation
2164------------------------------------------------------------------------------
2166-- | Use a 'Pipe' to transform a stream.
2168-- /Internal/
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
2186-- accommodate this.
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
2191-- extraction.
2193-- /Since 0.2.0/
2195-- /Since: 0.7.0 (Monad m constraint)/
2196{-# DEPRECATED scanx "Please use scanl followed by map instead." #-}
2197{-# INLINE scanx #-}
2198scanx :: (IsStream t, Monad m) => (x -> a -> x) -> x -> (x -> b) -> t m a -> t m b
2199scanx = P.scanlx'
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.
2208-- /Since: 0.4.0/
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
2218-- the stream.
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.
2224-- /Internal/
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.
2239-- @
2240-- > S.toList $ S.scanl' (+) 0 $ fromList [1,2,3,4]
2241-- [0,1,3,6,10]
2242-- @
2244-- @
2245-- > S.toList $ S.scanl' (flip (:)) [] $ S.fromList [1,2,3,4]
2246-- [[],[1],[2,1],[3,2,1],[4,3,2,1]]
2247-- @
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'@:
2261-- @
2262-- > S.foldl' (\\(s, p) x -> (s + x, p * x)) (0,1) $ S.fromList \[1,2,3,4]
2263-- (10,24)
2264-- @
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:
2269-- @
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]
2273-- (10,24)
2274-- @
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'
2282-- @since 0.2.0
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
2291-- @since 0.7.0
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.
2299-- /Since: 0.7.0/
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.
2311-- /Internal/
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.
2319-- /Internal/
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.
2327-- @since 0.6.0
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
2334-- is empty.
2336-- @
2337-- > S.toList $ S.scanl1 (+) $ fromList [1,2,3,4]
2338-- [1,3,6,10]
2339-- @
2341-- @since 0.6.0
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.
2352-- @since 0.7.0
2353{-# INLINE scan #-}
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.
2359-- @since 0.7.0
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)@.
2376-- /Internal/
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.
2384-- /Internal/
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.
2396-- @since 0.1.0
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
2402#else
2403filter :: IsStream t => (a -> Bool) -> t m a -> t m a
2404filter = K.filter
2405#endif
2407-- | Same as 'filter' but with a monadic predicate.
2409-- @since 0.4.0
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.
2416-- @since 0.6.0
2417{-# INLINE uniq #-}
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.
2424-- @since 0.6.0
2425{-# INLINE the #-}
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.
2431-- @since 0.1.0
2432{-# INLINE take #-}
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.
2439-- @since 0.1.0
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.
2446-- @since 0.4.0
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
2455-- stops.
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.
2465-- /Internal/
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.
2473-- @since 0.1.0
2474{-# INLINE drop #-}
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.
2481-- @since 0.1.0
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.
2488-- @since 0.4.0
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.
2505-- /Internal/
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------------------------------------------------------------------------------
2515-- |
2516-- @
2517-- mapM f = sequence . map f
2518-- @
2520-- Apply a monadic function to each element of the stream and replace it with
2521-- the output of the resulting action.
2523-- @
2524-- > drain $ S.mapM putStr $ S.fromList ["a", "b", "c"]
2525-- abc
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))
2532-- @
2534-- /Concurrent (do not use with 'parallely' on infinite streams)/
2536-- @since 0.1.0
2537{-# INLINE_EARLY mapM #-}
2538mapM :: (IsStream t, MonadAsync m) => (a -> m b) -> t m a -> t m b
2539mapM = K.mapM
2541{-# RULES "mapM serial" mapM = mapMSerial #-}
2542{-# INLINE mapMSerial #-}
2543mapMSerial :: Monad m => (a -> m b) -> SerialT m a -> SerialT m b
2544mapMSerial = Serial.mapM
2546-- |
2547-- @
2548-- sequence = mapM id
2549-- @
2551-- Replace the elements of a stream of monadic actions with the outputs of
2552-- those actions.
2554-- @
2555-- > drain $ S.sequence $ S.fromList [putStr "a", putStr "b", putStrLn "c"]
2556-- abc
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)
2563-- @
2565-- /Concurrent (do not use with 'parallely' on infinite streams)/
2567-- @since 0.1.0
2568{-# INLINE sequence #-}
2569sequence :: (IsStream t, MonadAsync m) => t m (m a) -> t m a
2570sequence m = fromStreamS $ S.sequence (toStreamS m)
2572-- $smapM_Notes
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
2585-- parseMany):
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''
2597-- /Internal/
2599{-# INLINE smapM #-}
2600smapM :: (IsStream t, Monad m) =>
2601 (s -> a -> m (s, b))
2602 -> m s
2603 -> t m a
2604 -> t m 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)
2611 -- stream
2612 let r = postscanlM'
2613 (\(s, _) a -> step s a)
2614 (fmap (,undefined) initial)
2615 stream
2616 in Serial.map snd r
2618------------------------------------------------------------------------------
2619-- Maybe Streams
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'.
2625-- Equivalent to:
2627-- @
2628-- mapMaybe f = S.map 'fromJust' . S.filter 'isJust' . S.map f
2629-- @
2631-- @since 0.3.0
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.
2638-- Equivalent to:
2640-- @
2641-- mapMaybeM f = S.map 'fromJust' . S.filter 'isJust' . S.mapM f
2642-- @
2644-- /Concurrent (do not use with 'parallely' on infinite streams)/
2646-- @since 0.3.0
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.
2659-- /Internal/
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
2672-- matters.
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)/
2681-- /Since: 0.1.1/
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.
2688-- /Internal/
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.
2702-- @
2703-- >>> S.toList $ S.trace putChar $ S.intersperseM (putChar '.' >> return ',') $ S.fromList "hello"
2704-- > h.,e.,l.,l.,o"h,e,l,l,o"
2705-- @
2707-- @since 0.5.0
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
2713-- first one.
2715-- @
2716-- >>> S.drain $ S.trace putChar $ S.intersperseM_ (putChar '.') $ S.fromList "hello"
2717-- > h.e.l.l.o
2718-- @
2720-- /Internal/
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.
2727-- @
2728-- > S.toList $ S.intersperse ',' $ S.fromList "hello"
2729-- "h,e,l,l,o"
2730-- @
2732-- @since 0.7.0
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.
2739-- @
2740-- >>> S.toList $ S.trace putChar $ S.intersperseSuffix (putChar '.' >> return ',') $ S.fromList "hello"
2741-- > h.,e.,l.,l.,o.,"h,e,l,l,o,"
2742-- @
2744-- /Internal/
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.
2751-- @
2752-- > S.mapM_ putChar $ S.intersperseSuffix_ (threadDelay 1000000) $ S.fromList "hello"
2753-- @
2755-- /Internal/
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.
2763-- @
2764-- >>> S.toList $ S.trace putChar $ S.interspersePrefix_ (putChar '.' >> return ',') $ S.fromList "hello"
2765-- > .h.e.l.l.o"hello"
2766-- @
2768-- See also: 'trace_'
2770-- /Concurrent/
2772-- /Internal/
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.
2783-- @
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)
2788-- @
2790-- /Internal/
2792{-# INLINE delay #-}
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
2799-- stream.
2801-- @
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)
2806-- @
2808-- /Internal/
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
2817-- stream.
2819-- @
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)
2824-- @
2826-- /Internal/
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.
2835-- @
2836-- > S.toList $ S.intersperseSuffixBySpan 2 (return ',') $ S.fromList "hello"
2837-- "he,ll,o,"
2838-- @
2840-- /Internal/
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@
2850-- elements.
2852-- @
2853-- > S.toList $ S.intersperseBySpan 2 (return ',') $ S.fromList "hello"
2854-- "he,ll,o"
2855-- @
2857-- @since 0.7.0
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@
2864-- seconds.
2866-- @
2867-- > S.drain $ S.interjectSuffix 1 (putChar ',') $ S.mapM (\\x -> threadDelay 1000000 >> putChar x) $ S.fromList "hello"
2868-- "h,e,l,l,o"
2869-- @
2871-- /Internal/
2872{-# INLINE interjectSuffix #-}
2873interjectSuffix
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@.
2882-- @
2883-- insertBy cmp x = 'mergeBy' cmp ('yield' x)
2884-- @
2886-- @
2887-- > S.toList $ S.insertBy compare 2 $ S.fromList [1,3,5]
2888-- [1,2,3,5]
2889-- @
2891-- @since 0.6.0
2892{-# INLINE insertBy #-}
2893insertBy ::
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------------------------------------------------------------------------------
2898-- Deleting
2899------------------------------------------------------------------------------
2901-- | Deletes the first occurrence of the element in the stream that satisfies
2902-- the given equality predicate.
2904-- @
2905-- > S.toList $ S.deleteBy (==) 3 $ S.fromList [1,3,3,5]
2906-- [1,3,5]
2907-- @
2909-- @since 0.6.0
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------------------------------------------------------------------------------
2915-- Zipping
2916------------------------------------------------------------------------------
2918-- |
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.
2924-- @
2925-- > S.toList $ S.indexed $ S.fromList "hello"
2926-- [(0,'h'),(1,'e'),(2,'l'),(3,'l'),(4,'o')]
2927-- @
2929-- @since 0.6.0
2930{-# INLINE indexed #-}
2931indexed :: (IsStream t, Monad m) => t m a -> t m (Int, a)
2932indexed = fromStreamD . D.indexed . toStreamD
2934-- |
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.
2941-- @
2942-- > S.toList $ S.indexedR 10 $ S.fromList "hello"
2943-- [(10,'h'),(9,'e'),(8,'l'),(7,'l'),(6,'o')]
2944-- @
2946-- @since 0.6.0
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
2960-- is consumed.
2962-- @
2963-- >>> S.mapM_ print $ S.timestampWith 0.01 $ S.delay 1 $ S.enumerateFromTo 1 3
2964-- @
2966-- /Internal/
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
2977-- consumed.
2979-- @
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)
2984-- @
2986-- /Internal/
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.
2997-- @
2998-- >>> S.mapM_ print $ S.timeIndexWith 0.01 $ S.delay 1 $ S.enumerateFromTo 1 3
2999-- @
3001-- /Internal/
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
3010-- consumed.
3012-- @
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)
3017-- @
3019-- /Internal/
3021{-# INLINE timeIndexed #-}
3022timeIndexed :: (IsStream t, MonadAsync m, Functor (t m))
3023 => t m a -> t m (RelTime64, a)
3024timeIndexed = timeIndexWith 0.01
3026------------------------------------------------------------------------------
3027-- Comparison
3028------------------------------------------------------------------------------
3030-- | Compare two streams for equality using an equality function.
3032-- @since 0.6.0
3033{-# INLINABLE eqBy #-}
3034eqBy :: (IsStream t, Monad m) => (a -> b -> Bool) -> t m a -> t m b -> m Bool
3035eqBy = P.eqBy
3037-- | Compare two streams lexicographically using a comparison function.
3039-- @since 0.6.0
3040{-# INLINABLE cmpBy #-}
3041cmpBy
3042 :: (IsStream t, Monad m)
3043 => (a -> b -> Ordering) -> t m a -> t m b -> m Ordering
3044cmpBy = P.cmpBy
3046------------------------------------------------------------------------------
3047-- Merge
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
3053-- first.
3055-- If the streams are sorted in ascending order, the resulting stream would
3056-- also remain sorted in ascending order.
3058-- @
3059-- > S.toList $ S.mergeBy compare (S.fromList [1,3,5]) (S.fromList [2,4,6,8])
3060-- [1,2,3,4,5,6,8]
3061-- @
3063-- @since 0.6.0
3064{-# INLINABLE mergeBy #-}
3065mergeBy ::
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:
3073-- @
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])
3076-- [2,1,2,2,2,1,1,1]
3077-- @
3079-- Merge two streams in a proportion of 2:1:
3081-- @
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
3087-- return $ head r
3089-- main = do
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])
3092-- print xs
3093-- @
3094-- @
3095-- [1,1,2,1,1,2,1,1,2]
3096-- @
3098-- @since 0.6.0
3099{-# INLINABLE mergeByM #-}
3100mergeByM
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 #-}
3108mergeEndByAny
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 #-}
3116mergeEndByFirst
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'@.
3127-- @
3128-- > S.toList $ S.merge (S.fromList [1,3,5]) (S.fromList [2,4,6,8])
3129-- [1,2,3,4,5,6,8]
3130-- @
3132-- @since 0.6.0
3133{-# INLINABLE merge #-}
3134merge ::
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).
3142-- @since 0.6.0
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).
3151-- @since 0.6.0
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------------------------------------------------------------------------------
3159-- Flattening Lists
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
3168-- seed.
3170-- /Compare 'foldMapWith'/
3172-- /Since: 0.7.0/
3174-- /Since: 0.8.0 (signature change)/
3175{-# INLINE concatMapWith #-}
3176concatMapWith
3177 :: IsStream t
3178 => (t m b -> t m b -> t m b)
3179 -> (a -> t m b)
3180 -> t m a
3181 -> 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.
3187-- @
3188-- concatSmapMWith combine f initial = concatMapWith combine id . smapM f initial
3189-- @
3191-- /Internal/
3193{-# INLINE concatSmapMWith #-}
3194concatSmapMWith
3195 :: (IsStream t, Monad m)
3196 => (t m b -> t m b -> t m b)
3197 -> (s -> a -> m (s, t m b))
3198 -> m s
3199 -> t m a
3200 -> 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.
3206-- @
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)
3211-- @
3213-- @since 0.6.0
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.
3220-- @
3221-- concat = concatMap id
3222-- @
3224-- /Internal/
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.
3239-- /Internal/
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
3258-- fromList "a,b,,,"
3259-- >>> interleave "abcd" ",," :: SerialT Identity Char
3260-- fromList "a,b,cd"
3262-- 'interleave' is dual to 'interleaveMin', it can be called @interleaveMax@.
3264-- Do not use at scale in concatMapWith.
3266-- /Internal/
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
3280-- fromList "a,b,c,"
3281-- >>> interleaveSuffix "abc" "," :: SerialT Identity Char
3282-- fromList "a,bc"
3284-- 'interleaveSuffix' is a dual of 'interleaveInfix'.
3286-- Do not use at scale in concatMapWith.
3288-- /Internal/
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
3299-- has finished.
3301-- >>> :set -XOverloadedStrings
3302-- >>> interleaveInfix "abc" ",,,," :: SerialT Identity Char
3303-- fromList "a,b,c"
3304-- >>> interleaveInfix "abc" "," :: SerialT Identity Char
3305-- fromList "a,bc"
3307-- 'interleaveInfix' is a dual of 'interleaveSuffix'.
3309-- Do not use at scale in concatMapWith.
3311-- /Internal/
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
3321-- stream.
3323-- >>> :set -XOverloadedStrings
3324-- >>> interleaveMin "ab" ",,,," :: SerialT Identity Char
3325-- fromList "a,b,"
3326-- >>> interleaveMin "abcd" ",," :: SerialT Identity Char
3327-- fromList "a,b,c"
3329-- 'interleaveMin' is dual to 'interleave'.
3331-- Do not use at scale in concatMapWith.
3333-- /Internal/
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.
3349-- /Internal/
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.
3359-- @since 0.6.0
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.
3367-- @
3368-- concatM = concat . yieldM
3369-- concatM = concat . lift -- requires @(MonadTrans t)@
3370-- concatM = join . lift -- requires @(MonadTrans t@, @Monad (t m))@
3371-- @
3373-- See also: 'concat', 'sequence'
3375-- /Internal/
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.
3385-- @since 0.7.0
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.
3393-- /Internal/
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
3401-- 'roundrobin'.
3403-- /Internal/
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.
3420-- /Internal/
3421{-# INLINE gintercalate #-}
3422gintercalate
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"]
3444-- > "abc def ghi"
3446-- /Internal/
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 ' '
3460-- /Internal/
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.
3469-- /Internal/
3470{-# INLINE gintercalateSuffix #-}
3471gintercalateSuffix
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"
3489-- /Internal/
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'
3503-- /Internal/
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------------------------------------------------------------------------------
3511-- Flattening Trees
3512------------------------------------------------------------------------------
3514-- | Like 'iterateM' but iterates after mapping a stream generator on the
3515-- output.
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':
3523-- @
3524-- iterateM f = iterateMapWith serial (yieldM . f) . yieldM
3525-- @
3527-- It can be used to traverse a tree structure. For example, to list a
3528-- directory tree:
3530-- @
3531-- Stream.iterateMapWith Stream.serial
3532-- (either Dir.toEither (const nil))
3533-- (yield (Left "tmp"))
3534-- @
3536-- /Internal/
3538{-# INLINE iterateMapWith #-}
3539iterateMapWith
3540 :: IsStream t
3541 => (t m a -> t m a -> t m a)
3542 -> (a -> t m a)
3543 -> t m a
3544 -> t m a
3545iterateMapWith combine f = concatMapWith combine go
3546 where
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------------------------------------------------------------------------------
3557-- Flattening Graphs
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.
3571-- See also: 'mfix'
3573-- /Internal/
3575{-# INLINE iterateSmapMWith #-}
3576iterateSmapMWith
3577 :: (IsStream t, Monad m)
3578 => (t m a -> t m a -> t m a)
3579 -> (b -> a -> m (b, t m a))
3580 -> m b
3581 -> t m a
3582 -> t m a
3583iterateSmapMWith combine f initial stream =
3584 concatMap (\b -> concatMapWith combine (go b) stream) (yieldM initial)
3586 where
3588 go b a = yield a `combine` feedback b a
3590 feedback b a =
3591 concatMap
3592 (\(b1, s) -> concatMapWith combine (go b1) s)
3593 (yieldM $ f b a)
3595------------------------------------------------------------------------------
3596-- Either streams
3597------------------------------------------------------------------------------
3599-- | Discard 'Right's and unwrap 'Left's in an 'Either' stream.
3601-- /Internal/
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.
3608-- /Internal/
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
3614-- 'iterateMapWith':
3616-- @
3617-- iterateMapLeftsWith combine f = iterateMapWith combine (either f (const nil))
3618-- @
3620-- To traverse a directory tree:
3622-- @
3623-- iterateMapLeftsWith serial Dir.toEither (yield (Left "tmp"))
3624-- @
3626-- /Internal/
3628{-# INLINE iterateMapLeftsWith #-}
3629iterateMapLeftsWith
3630 :: IsStream t
3631 => (t m (Either a b) -> t m (Either a b) -> t m (Either a b))
3632 -> (a -> t m (Either a b))
3633 -> t m (Either a b)
3634 -> t m (Either a b)
3635iterateMapLeftsWith combine f = iterateMapWith combine (either f (const K.nil))
3637------------------------------------------------------------------------------
3638-- Parsing
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
3648-- output stream.
3650-- This is the streaming equivalent of the 'Streamly.Internal.Data.Parser.many'
3651-- parse combinator.
3653-- >>> S.toList $ S.parseMany (PR.take 2 $ PR.fromFold FL.sum) $ S.fromList [1..10]
3654-- > [3,7,11,15,19]
3656-- >>> S.toList $ S.parseMany (PR.line FL.toList) $ S.fromList "hello\nworld"
3657-- > ["hello\n","world"]
3659-- /Internal
3661{-# INLINE parseMany #-}
3662parseMany
3663 :: (IsStream t, MonadThrow m)
3664 => Parser m a b
3665 -> t m a
3666 -> t m b
3667parseMany p m =
3668 D.fromStreamD $ D.parseMany (PRK.fromParserK p) (D.toStreamD m)
3670{-# INLINE parseManyD #-}
3671parseManyD
3672 :: (IsStream t, MonadThrow m)
3673 => PRD.Parser m a b
3674 -> t m a
3675 -> t m b
3676parseManyD p 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.
3685-- /Unimplemented/
3687{-# INLINE parseManyTill #-}
3688parseManyTill ::
3689 -- (IsStream t, MonadThrow m) =>
3690 Parser m a b
3691 -> Parser m a x
3692 -> t m a
3693 -> t m b
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.
3706-- /Internal/
3708{-# INLINE parseIterate #-}
3709parseIterate
3710 :: (IsStream t, MonadThrow m)
3711 => (b -> Parser m a b)
3712 -> b
3713 -> t m a
3714 -> t m 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------------------------------------------------------------------------------
3727-- Binary APIs
3728------------------------------------------------------------------------------
3731------------------------------------------------------------------------------
3732-- N-ary APIs
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 #-}
3768groupScan
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)
3778-- > [3,7,11,15,19]
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.
3783-- @since 0.7.0
3784{-# INLINE chunksOf #-}
3785chunksOf
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)
3790-- |
3792-- /Internal/
3793{-# INLINE chunksOf2 #-}
3794chunksOf2
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)
3806-- /Internal/
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
3815-- > [3,7,11,15,19]
3817-- | Group the input stream into windows of @n@ second each and then fold each
3818-- group using the provided fold function.
3820-- @since 0.7.0
3821{-# INLINE intervalsOf #-}
3822intervalsOf
3823 :: (IsStream t, MonadAsync m)
3824 => Double -> Fold m a b -> t m a -> t m b
3825intervalsOf n f xs =
3826 splitWithSuffix isNothing (FL.lcatMaybes f)
3827 (interjectSuffix n (return Nothing) (Serial.map Just xs))
3829------------------------------------------------------------------------------
3830-- N-ary APIs
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]]
3843-- @since 0.7.0
3844{-# INLINE groupsBy #-}
3845groupsBy
3846 :: (IsStream t, Monad m)
3847 => (a -> a -> Bool)
3848 -> Fold m a b
3849 -> t m a
3850 -> t m b
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
3859-- @f@.
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]]
3864-- @since 0.7.0
3865{-# INLINE groupsByRolling #-}
3866groupsByRolling
3867 :: (IsStream t, Monad m)
3868 => (a -> a -> Bool)
3869 -> Fold m a b
3870 -> t m a
3871 -> t m b
3872groupsByRolling cmp f m = D.fromStreamD $ D.groupsRollingBy cmp f (D.toStreamD m)
3874-- |
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]
3881-- > [[1,1],[2,2]]
3883-- @since 0.7.0
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
3895-- as argument.
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:
3904-- @
3905-- "--.--" => "--" "--"
3906-- "--." => "--" ""
3907-- ".--" => "" "--"
3908-- @
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' (== '.') ""
3917-- [""]
3919-- >>> splitOn' (== '.') "."
3920-- ["",""]
3922-- >>> splitOn' (== '.') ".a"
3923-- > ["","a"]
3925-- >>> splitOn' (== '.') "a."
3926-- > ["a",""]
3928-- >>> splitOn' (== '.') "a.b"
3929-- > ["a","b"]
3931-- >>> splitOn' (== '.') "a..b"
3932-- > ["a","","b"]
3934-- @since 0.7.0
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 #-}
3941splitOn
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:
3952-- @
3953-- "--.--." => "--" "--"
3954-- "--.--" => "--" "--"
3955-- ".--." => "" "--"
3956-- @
3958-- > splitOnSuffix' p xs = S.toList $ S.splitSuffixBy p (FL.toList) (S.fromList xs)
3960-- >>> splitOnSuffix' (== '.') ""
3961-- []
3963-- >>> splitOnSuffix' (== '.') "."
3964-- [""]
3966-- >>> splitOnSuffix' (== '.') "a"
3967-- ["a"]
3969-- >>> splitOnSuffix' (== '.') ".a"
3970-- > ["","a"]
3972-- >>> splitOnSuffix' (== '.') "a."
3973-- > ["a"]
3975-- >>> splitOnSuffix' (== '.') "a.b"
3976-- > ["a","b"]
3978-- >>> splitOnSuffix' (== '.') "a.b."
3979-- > ["a","b"]
3981-- >>> splitOnSuffix' (== '.') "a..b.."
3982-- > ["a","","b",""]
3984-- > lines = splitOnSuffix (== '\n')
3986-- @since 0.7.0
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 #-}
3993splitOnSuffix
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
4002-- separated text.
4004-- > wordsBy' p xs = S.toList $ S.wordsBy p (FL.toList) (S.fromList xs)
4006-- >>> wordsBy' (== ',') ""
4007-- > []
4009-- >>> wordsBy' (== ',') ","
4010-- > []
4012-- >>> wordsBy' (== ',') ",a,,b,"
4013-- > ["a","b"]
4015-- > words = wordsBy isSpace
4017-- @since 0.7.0
4019-- It is equivalent to splitting in any of the infix/prefix/suffix styles
4020-- followed by removal of empty segments.
4021{-# INLINE wordsBy #-}
4022wordsBy
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
4029-- splits.
4031-- > splitWithSuffix' p xs = S.toList $ S.splitWithSuffix p (FL.toList) (S.fromList xs)
4033-- >>> splitWithSuffix' (== '.') ""
4034-- []
4036-- >>> splitWithSuffix' (== '.') "."
4037-- ["."]
4039-- >>> splitWithSuffix' (== '.') "a"
4040-- ["a"]
4042-- >>> splitWithSuffix' (== '.') ".a"
4043-- > [".","a"]
4045-- >>> splitWithSuffix' (== '.') "a."
4046-- > ["a."]
4048-- >>> splitWithSuffix' (== '.') "a.b"
4049-- > ["a.","b"]
4051-- >>> splitWithSuffix' (== '.') "a.b."
4052-- > ["a.","b."]
4054-- >>> splitWithSuffix' (== '.') "a..b.."
4055-- > ["a.",".","b.","."]
4057-- @since 0.7.0
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 #-}
4063splitWithSuffix
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]
4079-- > [[1,2,3,3,4]]
4081-- >>> splitList [1] [1,2,3,3,4]
4082-- > [[],[2,3,3,4]]
4084-- >>> splitList [4] [1,2,3,3,4]
4085-- > [[1,2,3,3],[]]
4087-- >>> splitList [2] [1,2,3,3,4]
4088-- > [[1],[3,3,4]]
4090-- >>> splitList [3] [1,2,3,3,4]
4091-- > [[1,2],[],[4]]
4093-- >>> splitList [3,3] [1,2,3,3,4]
4094-- > [[1,2],[4]]
4096-- >>> splitList [1,2,3,3,4] [1,2,3,3,4]
4097-- > [[],[]]
4099-- | Like 'splitOn' but the separator is a sequence of elements instead of a
4100-- single element.
4102-- For illustration, let's define a function that operates on pure lists:
4104-- @
4105-- splitOnSeq' pat xs = S.toList $ S.splitOnSeq (A.fromList pat) (FL.toList) (S.fromList xs)
4106-- @
4108-- >>> splitOnSeq' "" "hello"
4109-- > ["h","e","l","l","o"]
4111-- >>> splitOnSeq' "hello" ""
4112-- > [""]
4114-- >>> splitOnSeq' "hello" "hello"
4115-- > ["",""]
4117-- >>> splitOnSeq' "x" "hello"
4118-- > ["hello"]
4120-- >>> splitOnSeq' "h" "hello"
4121-- > ["","ello"]
4123-- >>> splitOnSeq' "o" "hello"
4124-- > ["hell",""]
4126-- >>> splitOnSeq' "e" "hello"
4127-- > ["h","llo"]
4129-- >>> splitOnSeq' "l" "hello"
4130-- > ["he","","o"]
4132-- >>> splitOnSeq' "ll" "hello"
4133-- > ["he","o"]
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
4144-- /Internal/
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 #-}
4152splitOnSeq
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.splitOnSeq 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 #-}
4161splitOnAny
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_ "." ""
4173-- []
4175-- >>> splitSuffixOn_ "." "."
4176-- [""]
4178-- >>> splitSuffixOn_ "." "a"
4179-- ["a"]
4181-- >>> splitSuffixOn_ "." ".a"
4182-- > ["","a"]
4184-- >>> splitSuffixOn_ "." "a."
4185-- > ["a"]
4187-- >>> splitSuffixOn_ "." "a.b"
4188-- > ["a","b"]
4190-- >>> splitSuffixOn_ "." "a.b."
4191-- > ["a","b"]
4193-- >>> splitSuffixOn_ "." "a..b.."
4194-- > ["a","","b",""]
4196-- > lines = splitSuffixOn "\n"
4198-- /Internal/
4199{-# INLINE splitOnSuffixSeq #-}
4200splitOnSuffixSeq
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 #-}
4210wordsOn
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" ""
4226-- > [""]
4228-- >>> splitOn'_ "hello" "hello"
4229-- > ["","hello",""]
4231-- >>> splitOn'_ "x" "hello"
4232-- > ["hello"]
4234-- >>> splitOn'_ "h" "hello"
4235-- > ["","h","ello"]
4237-- >>> splitOn'_ "o" "hello"
4238-- > ["hell","o",""]
4240-- >>> splitOn'_ "e" "hello"
4241-- > ["h","e","llo"]
4243-- >>> splitOn'_ "l" "hello"
4244-- > ["he","l","","l","o"]
4246-- >>> splitOn'_ "ll" "hello"
4247-- > ["he","ll","o"]
4249-- /Internal/
4250{-# INLINE splitBySeq #-}
4251splitBySeq
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'_ "." ""
4262-- [""]
4264-- >>> splitSuffixOn'_ "." "."
4265-- ["."]
4267-- >>> splitSuffixOn'_ "." "a"
4268-- ["a"]
4270-- >>> splitSuffixOn'_ "." ".a"
4271-- > [".","a"]
4273-- >>> splitSuffixOn'_ "." "a."
4274-- > ["a."]
4276-- >>> splitSuffixOn'_ "." "a.b"
4277-- > ["a.","b"]
4279-- >>> splitSuffixOn'_ "." "a.b."
4280-- > ["a.","b."]
4282-- >>> splitSuffixOn'_ "." "a..b.."
4283-- > ["a.",".","b.","."]
4285-- /Internal/
4286{-# INLINE splitWithSuffixSeq #-}
4287splitWithSuffixSeq
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 #-}
4297splitSuffixOnAny
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------------------------------------------------------------------------------
4305-- Nested Split
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.
4320-- /Internal/
4321{-# INLINE splitInnerBy #-}
4322splitInnerBy
4323 :: (IsStream t, Monad m)
4324 => (f a -> m (f a, Maybe (f a))) -- splitter
4325 -> (f a -> f a -> m (f a)) -- joiner
4326 -> t m (f a)
4327 -> t m (f a)
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
4332-- a suffix style.
4334-- /Internal/
4335{-# INLINE splitInnerBySuffix #-}
4336splitInnerBySuffix
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
4340 -> t m (f a)
4341 -> t m (f a)
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 #-}
4354reassembleBy
4355 :: (IsStream t, Monad m)
4356 => Fold m a b
4357 -> (a -> a -> Int)
4358 -> t m a
4359 -> t m b
4360reassembleBy = undefined
4363------------------------------------------------------------------------------
4364-- Distributing
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.
4371-- @
4372-- Fold m a b
4373-- |
4374-- -----stream m a ---------------stream m a-----
4376-- @
4378-- @
4379-- > S.drain $ S.tap (FL.drainBy print) (S.enumerateFromTo 1 2)
4380-- 1
4381-- 2
4382-- @
4384-- Compare with 'trace'.
4386-- @since 0.7.0
4387{-# INLINE tap #-}
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.
4396-- @
4397-- >>> S.drain $ S.tapOffsetEvery 0 2 (FL.mapM print FL.toList) $ S.enumerateFromTo 0 10
4398-- > [0,2,4,6,8,10]
4399-- @
4401-- /Internal/
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.
4413-- @
4414-- Stream m a -> m b
4415-- |
4416-- -----stream m a ---------------stream m a-----
4418-- @
4420-- @
4421-- > S.drain $ S.tapAsync (S.mapM_ print) (S.enumerateFromTo 1 2)
4422-- 1
4423-- 2
4424-- @
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'.
4435-- /Internal/
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:
4448-- @
4449-- > S.drain $ S.pollCounts (const True) (S.rollingMap (-) . S.delayPost 1) (FL.drainBy print)
4450-- $ S.enumerateFrom 0
4451-- @
4453-- Note: This may not work correctly on 32-bit machines.
4455-- /Internal/
4457{-# INLINE pollCounts #-}
4458pollCounts ::
4459 (IsStream t, MonadAsync m)
4460 => (a -> Bool)
4461 -> (t m Int -> t m Int)
4462 -> Fold m Int b
4463 -> t m a
4464 -> t m a
4465pollCounts predicate transf f xs =
4466 D.fromStreamD
4467 $ D.pollCounts predicate (D.toStreamD . transf . D.fromStreamD) f
4468 $ D.toStreamD xs
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.
4477-- @
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
4482-- @
4484-- Note: This may not work correctly on 32-bit machines.
4486-- /Internal/
4487{-# INLINE tapRate #-}
4488tapRate ::
4489 (IsStream t, MonadAsync m, MonadCatch m)
4490 => Double
4491 -> (Int -> m b)
4492 -> t m a
4493 -> t m a
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.
4499-- @
4500-- > S.drain $ S.trace print (S.enumerateFromTo 1 2)
4501-- 1
4502-- 2
4503-- @
4505-- Compare with 'tap'.
4507-- @since 0.7.0
4508{-# INLINE trace #-}
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.
4515-- @
4516-- > S.drain $ S.trace_ (print "got here") (S.enumerateFromTo 1 2)
4517-- "got here"
4518-- "got here"
4519-- @
4521-- See also: 'trace', 'interspersePrefix_'
4523-- /Internal/
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
4544-- or timestamps.
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
4558 -> t m (k, b)
4559classifySlidingChunks wsize wslide (Fold step initial extract) str
4560 = undefined
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
4575 -> t m (k, b)
4576classifySlidingSessions tick interval slide (Fold step initial extract) str
4577 = undefined
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.
4599slidingChunkBuffer
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
4604 -> t m a
4605 -> t m 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.
4612slidingSessionBuffer
4613 :: (IsStream t, Monad m, Ord a, Storable a)
4614 => Int -- window size
4615 -> Int -- tick size
4616 -> Fold m (RTree a, Array a) b
4617 -> t m a
4618 -> t m 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 #-}
4630classifyChunksBy
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
4636 -> t m (k, b)
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
4649 -> t m (k, b)
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
4662#undef Type
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.
4691-- /Internal/
4694-- XXX Perhaps we should use an "Event a" type to represent timestamped data.
4695{-# INLINABLE classifySessionsBy #-}
4696classifySessionsBy
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
4710 where
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)
4717 , sessionCount = 0
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:
4725 --
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
4729 -- old ones.
4730 --
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
4736 -- size
4737 --
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.
4743 --
4744 -- XXX if the key is an Int, we can also use an IntMap for slightly
4745 -- better performance.
4746 --
4747 let curTime = max sessionEventTime timestamp
4748 accumulate v = do
4749 old <- case v of
4750 Nothing -> initial
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
4757 res <- extract fres
4758 case res of
4759 Left x -> do
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.
4765 --
4766 let (mp, cnt) = case mOld of
4767 Nothing -> (sessionKeyValueMap, sessionCount)
4768 Just _ -> (Map.delete key sessionKeyValueMap
4769 , sessionCount - 1)
4770 return $ session
4771 { sessionCurTime = curTime
4772 , sessionEventTime = curTime
4773 , sessionCount = cnt
4774 , sessionKeyValueMap = mp
4775 , sessionOutputStream = yield (key, x)
4777 Right _ -> do
4778 (hp1, mp1, out1, cnt1) <- do
4779 let vars = (sessionTimerHeap, sessionKeyValueMap,
4780 K.nil, sessionCount)
4781 case mOld of
4782 -- inserting new entry
4783 Nothing -> do
4784 -- Eject a session from heap and map is needed
4785 eject <- ejectPred sessionCount
4786 (hp, mp, out, cnt) <-
4787 if eject
4788 then ejectOne vars
4789 else return vars
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) <-
4815 ejectAll
4816 ( sessionTimerHeap
4817 , sessionKeyValueMap
4818 , K.nil
4819 , sessionCount
4821 return $ session
4822 { sessionCount = count
4823 , sessionTimerHeap = hp'
4824 , sessionKeyValueMap = mp'
4825 , sessionOutputStream = out
4828 fromEither e =
4829 case e of
4830 Left x -> x
4831 Right x -> x
4833 -- delete from map and output the fold accumulator
4834 ejectEntry hp mp out cnt acc key = do
4835 sess <- extract acc
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
4842 case hres of
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
4847 ejectAll r
4848 Nothing -> do
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
4854 case hres of
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
4862 else
4863 -- reset the session timeout and continue
4864 let hp2 = H.insert (Entry expiry1 key) hp1
4865 in ejectOne (hp2, mp, out, cnt)
4866 Nothing -> do
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
4873 return $ session
4874 { sessionCurTime = curTime
4875 , sessionCount = count
4876 , sessionTimerHeap = hp'
4877 , sessionKeyValueMap = mp'
4878 , sessionOutputStream = out
4881 where
4883 ejectLoop hp mp out !cnt = do
4884 let hres = H.uncons hp
4885 case hres of
4886 Just (Entry expiry key, hp1) -> do
4887 (eject, force) <-
4888 if curTime >= expiry
4889 then return (True, False)
4890 else do
4891 r <- ejectPred cnt
4892 return (r, r)
4893 if eject
4894 then
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
4900 then do
4901 (hp2,mp1,out1,cnt1) <-
4902 ejectEntry hp1 mp out cnt acc key
4903 ejectLoop hp2 mp1 out1 cnt1
4904 else
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)
4909 Nothing -> do
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
4915 timer = do
4916 liftIO $ threadDelay (round $ tick * 1000000)
4917 return Nothing
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.
4926-- @
4927-- classifyKeepAliveSessions timeout pred = classifySessionsBy 1 timeout True pred
4928-- @
4930-- /Internal/
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
4939 -> t m (k, b)
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.
4960-- @since 0.7.0
4961{-# INLINABLE classifyChunksOf #-}
4962classifyChunksOf
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
4967 -> t m (k, b)
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.
4984-- @
4985-- classifySessionsOf interval pred = classifySessionsBy 1 interval False pred
4986-- @
4988-- @
4989-- >>> S.mapM_ print
4990-- $ S.classifySessionsOf 3 (const (return False)) (fmap Right FL.toList)
4991-- $ S.map (\(ts,(k,a)) -> (k, a, ts))
4992-- $ S.timestamped
4993-- $ S.delay 1
4994-- $ (,) <$> S.fromList [1,2,3] <*> S.fromList [1,2,3]
4995-- @
4997-- /Internal/
4999{-# INLINABLE classifySessionsOf #-}
5000classifySessionsOf
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
5006 -> t m (k, b)
5007classifySessionsOf interval =
5008 classifySessionsBy 1 interval False
5010------------------------------------------------------------------------------
5011-- Exceptions
5012------------------------------------------------------------------------------
5014-- | Run a side effect before the stream yields its first element.
5016-- > before action xs = 'nilM' action <> xs
5018-- @since 0.7.0
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'.
5030-- /Internal/
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.
5039-- @since 0.7.0
5041{-# INLINE after #-}
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.
5048-- @since 0.7.0
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'.
5059-- /Internal/
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.
5068-- @since 0.7.0
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'.
5082-- /Internal/
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.
5095-- @since 0.7.0
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.
5106-- @since 0.7.0
5107{-# INLINE handle #-}
5108handle :: (IsStream t, MonadCatch m, Exception e)
5109 => (e -> t m a) -> t m a -> t m a
5110handle handler xs =
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'
5118-- /Unimplemented/
5121concatMapEitherWith
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))
5125 -> t m a
5126 -> t m b
5127concatMapEitherWith = undefined
5130------------------------------------------------------------------------------
5131-- Generalize the underlying monad
5132------------------------------------------------------------------------------
5134-- | Transform the inner monad of a stream using a natural transformation.
5136-- / Internal/
5138{-# INLINE hoist #-}
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.
5145-- / Internal/
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
5156-- transformer @tr@.
5158-- / Internal/
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'.
5171-- / Internal/
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'
5181-- / Internal/
5183{-# INLINE usingReaderT #-}
5184usingReaderT
5185 :: (Monad m, IsStream t)
5186 => m r
5187 -> (t (ReaderT r m) a -> t (ReaderT r m) a)
5188 -> t m a
5189 -> t 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
5199-- safe.
5201-- / Internal/
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
5210-- safe.
5212-- See also: 'scanl''
5214-- / Internal/
5216{-# INLINE usingStateT #-}
5217usingStateT
5218 :: Monad m
5219 => m s
5220 -> (SerialT (StateT s m) a -> SerialT (StateT s m) a)
5221 -> SerialT m a
5222 -> SerialT 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
5229-- safe.
5231-- / Internal/
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)