on 135f28f help sign in
1681 lines 53 kB history raw
1-- |
2-- Module : Streamly.Internal.Data.Stream.IsStream.Transform
3-- Copyright : (c) 2017 Composewell Technologies
4-- License : BSD-3-Clause
5-- Maintainer : streamly@composewell.com
6-- Stability : experimental
7-- Portability : GHC
9module Streamly.Internal.Data.Stream.IsStream.Transform
10 (
11 -- * Piping
12 -- | Pass through a 'Pipe'.
13 transform
15 -- * Folding
16 , foldrS
17 , foldrSShared
18 , foldrT
20 -- * Mapping
21 -- | Stateless one-to-one maps.
22 , map
23 , sequence
24 , mapM
25 , smapM
27 -- * Mapping Side Effects (Observation)
28 -- | See also the intersperse*_ combinators.
29 , trace
30 , trace_
31 , tap
32 , tapOffsetEvery
33 , tapAsync
34 , tapAsyncK
35 , distributeAsync_
36 , tapRate
37 , pollCounts
39 -- * Scanning By 'Fold'
40 , scan
41 , postscan
43 -- * Scanning
44 -- | Left scans. Stateful, mostly one-to-one maps.
45 , scanl'
46 , scanlM'
47 , scanlMAfter'
48 , postscanl'
49 , postscanlM'
50 , prescanl'
51 , prescanlM'
52 , scanl1'
53 , scanl1M'
55 -- XXX Once we have pipes the contravariant transformations can be
56 -- represented by attaching pipes before a transformation.
57 --
58 -- , lscanl'
59 -- , lscanlM'
60 -- , lscanl1'
61 -- , lscanl1M'
62 --
63 -- , lpostscanl'
64 -- , lpostscanlM'
65 -- , lprescanl'
66 -- , lprescanlM'
68 -- * Filtering
69 -- | Produce a subset of the stream using criteria based on the values of
70 -- the elements. We can use a concatMap and scan for filtering but these
71 -- combinators are more efficient and convenient.
73 , with
74 , deleteBy
75 , filter
76 , filterM
77 , uniq
78 , uniqBy
79 , nubBy
80 , nubWindowBy
81 , prune
82 , repeated
84 -- * Trimming
85 -- | Produce a subset of the stream trimmed at ends.
87 , take
88 , takeInterval
89 , takeLast
90 , takeLastInterval
91 , takeWhile
92 , takeWhileM
93 , takeWhileLast
94 , takeWhileAround
95 , drop
96 , dropInterval
97 , dropLast
98 , dropLastInterval
99 , dropWhile
100 , dropWhileM
101 , dropWhileLast
102 , dropWhileAround
104 -- * Inserting Elements
105 -- | Produce a superset of the stream. This is the opposite of
106 -- filtering/sampling. We can always use concatMap and scan for inserting
107 -- but these combinators are more efficient and convenient.
109 -- Element agnostic (Opposite of sampling)
110 , intersperse
111 , intersperseM -- XXX naming
112 , intersperseBySpan
114 , intersperseSuffix
115 , intersperseSuffixBySpan
116 , interjectSuffix
118 -- , interspersePrefix
119 -- , interspersePrefixBySpan
121 -- * Inserting Side Effects/Time
122 , intersperseM_ -- XXX naming
123 , delay
124 , intersperseSuffix_
125 , delayPost
126 , interspersePrefix_
127 , delayPre
129 -- * Element Aware Insertion
130 -- | Opposite of filtering
131 , insertBy
132 -- , intersperseByBefore
133 -- , intersperseByAfter
135 -- * Reordering
136 , reverse
137 , reverse'
138 , reassembleBy
140 -- * Position Indexing
141 , indexed
142 , indexedR
144 -- * Time Indexing
145 , timestamped
146 , timestampWith
147 -- , timestampedR -- timer
148 , timeIndexed
149 , timeIndexWith
151 -- * Searching
152 , findIndices -- XXX indicesBy
153 , elemIndices -- XXX indicesOf
155 -- * Rolling map
156 -- | Map using the previous element.
157 , rollingMapM
158 , rollingMap
159 , rollingMap2
161 -- * Maybe Streams
162 -- Move these to Streamly.Data.Maybe.Stream?
163 , catMaybes -- XXX justs (like lefts/rights)
164 , mapMaybe
165 , mapMaybeM
167 -- * Either Streams
168 -- Move these to Streamly.Data.Either.Stream?
169 , lefts
170 , rights
171 , both
173 -- * Concurrent Evaluation
174 -- ** Concurrent Pipelines
175 -- | Run streaming stages concurrently.
177 , mkAsync
178 , mkParallel
179 , applyAsync
180 , (|$)
181 , (|&)
183 -- ** Concurrency Control
184 , maxThreads
186 -- ** Buffering and Sampling
187 -- | Evaluate strictly using a buffer of results. When the buffer becomes
188 -- full we can block, drop the new elements, drop the oldest element and
189 -- insert the new at the end or keep dropping elements uniformly to match
190 -- the rate of the consumer.
191 , maxBuffer
192 , sampleOld
193 , sampleNew
194 , sampleRate
196 -- ** Rate Limiting
197 -- | Evaluate the stream at uniform intervals to maintain a specified
198 -- evaluation rate.
199 , Rate (..)
200 , rate
201 , avgRate
202 , minRate
203 , maxRate
204 , constRate
206 -- * Diagnostics
207 , inspectMode
209 -- * Deprecated
210 , scanx
211 )
212where
214#include "inline.hs"
216import Control.Concurrent (threadDelay)
217import Control.Monad (void)
218import Control.Monad.Catch (MonadCatch)
219import Control.Monad.IO.Class (MonadIO(..))
220import Control.Monad.Trans.Class (MonadTrans(..))
221import Data.Either (isLeft, isRight, fromLeft, fromRight)
222import Data.Kind (Type)
223import Data.Maybe (isJust, fromJust)
224import Streamly.Internal.Data.Fold.Type (Fold (..))
225import Streamly.Internal.Data.Pipe.Type (Pipe (..))
226import Streamly.Internal.Data.Stream.IsStream.Combinators
227 ( inspectMode, maxBuffer, maxThreads, rate, avgRate, minRate
228 , maxRate, constRate)
229import Streamly.Internal.Data.Stream.IsStream.Common
230 ( absTimesWith
231 , drop
232 , findIndices
233 , map
234 , postscanlM'
235 , relTimesWith
236 , reverse
237 , reverse'
238 , scanlMAfter'
239 , smapM
240 , take
241 , takeWhile
242 , interjectSuffix
243 , intersperseM
244 , mkAsync
245 , mkParallel
246 , zipWith
247 )
248import Streamly.Internal.Control.Concurrent (MonadAsync)
249import Streamly.Internal.Data.Stream.IsStream.Type
250 (IsStream(..), fromStreamS, toStreamS, fromStreamD, toStreamD, toConsK)
251import Streamly.Internal.Data.Stream.Serial (SerialT)
252import Streamly.Internal.Data.SVar (Rate(..))
253import Streamly.Internal.Data.Time.Units (TimeUnit64, AbsTime, RelTime64)
255import qualified Streamly.Internal.Data.Fold as FL
256import qualified Streamly.Internal.Data.Stream.Parallel as Par
257import qualified Streamly.Internal.Data.Stream.Serial as Serial
258import qualified Streamly.Internal.Data.Stream.StreamD as D
259import qualified Streamly.Internal.Data.Stream.StreamK.Type as K
260#ifdef USE_STREAMK_ONLY
261import qualified Streamly.Internal.Data.Stream.StreamK as S
262#else
263import qualified Streamly.Internal.Data.Stream.StreamD as S
264#endif
265import qualified Prelude
267import Prelude hiding
268 ( filter, drop, dropWhile, take, takeWhile, foldr, map, mapM, sequence
269 , reverse, foldr1 , scanl, scanl1, zipWith)
271--
272-- $setup
273-- >>> :m
274-- >>> import Control.Concurrent (threadDelay)
275-- >>> import Data.Function ((&))
276-- >>> import Streamly.Prelude ((|$))
277-- >>> import Prelude hiding ( filter, drop, dropWhile, take, takeWhile, foldr, map, mapM, sequence, reverse, foldr1 , scanl, scanl1)
278-- >>> import qualified Streamly.Prelude as Stream
279-- >>> import Streamly.Internal.Data.Stream.IsStream as Stream
280-- >>> import qualified Streamly.Data.Fold as Fold
281-- >>> import qualified Streamly.Internal.Data.Fold as Fold
282-- >>> import System.IO (stdout, hSetBuffering, BufferMode(LineBuffering))
283--
284-- >>> hSetBuffering stdout LineBuffering
286------------------------------------------------------------------------------
287-- Piping
288------------------------------------------------------------------------------
290-- | Use a 'Pipe' to transform a stream.
291--
292-- /Pre-release/
293--
294{-# INLINE transform #-}
295transform :: (IsStream t, Monad m) => Pipe m a b -> t m a -> t m b
296transform pipe xs = fromStreamD $ D.transform pipe (toStreamD xs)
298------------------------------------------------------------------------------
299-- Transformation Folds
300------------------------------------------------------------------------------
302-- | Right fold to a streaming monad.
303--
304-- > foldrS Stream.cons Stream.nil === id
305--
306-- 'foldrS' can be used to perform stateless stream to stream transformations
307-- like map and filter in general. It can be coupled with a scan to perform
308-- stateful transformations. However, note that the custom map and filter
309-- routines can be much more efficient than this due to better stream fusion.
310--
311-- >>> Stream.toList $ Stream.foldrS Stream.cons Stream.nil $ Stream.fromList [1..5]
312-- [1,2,3,4,5]
313--
314-- Find if any element in the stream is 'True':
315--
316-- >>> Stream.toList $ Stream.foldrS (\x xs -> if odd x then return True else xs) (return False) $ (Stream.fromList (2:4:5:undefined) :: Stream.SerialT IO Int)
317-- [True]
318--
319-- Map (+2) on odd elements and filter out the even elements:
320--
321-- >>> Stream.toList $ Stream.foldrS (\x xs -> if odd x then (x + 2) `Stream.cons` xs else xs) Stream.nil $ (Stream.fromList [1..5] :: Stream.SerialT IO Int)
322-- [3,5,7]
323--
324-- 'foldrM' can also be represented in terms of 'foldrS', however, the former
325-- is much more efficient:
326--
327-- > foldrM f z s = runIdentityT $ foldrS (\x xs -> lift $ f x (runIdentityT xs)) (lift z) s
328--
329-- /Pre-release/
330{-# INLINE foldrS #-}
331foldrS :: IsStream t => (a -> t m b -> t m b) -> t m b -> t m a -> t m b
332foldrS f z xs =
333 fromStream
334 $ K.foldrS
335 (\y ys -> toStream $ f y (fromStream ys))
336 (toStream z)
337 (toStream xs)
339{-# INLINE foldrSShared #-}
340foldrSShared :: IsStream t => (a -> t m b -> t m b) -> t m b -> t m a -> t m b
341foldrSShared f z xs =
342 fromStream
343 $ K.foldrSShared
344 (\y ys -> toStream $ f y (fromStream ys))
345 (toStream z)
346 (toStream xs)
348-- | Right fold to a transformer monad. This is the most general right fold
349-- function. 'foldrS' is a special case of 'foldrT', however 'foldrS'
350-- implementation can be more efficient:
351--
352-- > foldrS = foldrT
353-- > foldrM f z s = runIdentityT $ foldrT (\x xs -> lift $ f x (runIdentityT xs)) (lift z) s
354--
355-- 'foldrT' can be used to translate streamly streams to other transformer
356-- monads e.g. to a different streaming type.
357--
358-- /Pre-release/
359{-# INLINE foldrT #-}
360foldrT :: (IsStream t, Monad m, Monad (s m), MonadTrans s)
361 => (a -> s m b -> s m b) -> s m b -> t m a -> s m b
362foldrT f z s = S.foldrT f z (toStreamS s)
364------------------------------------------------------------------------------
365-- Transformation by Mapping
366------------------------------------------------------------------------------
368-- |
369-- @
370-- mapM f = sequence . map f
371-- @
372--
373-- Apply a monadic function to each element of the stream and replace it with
374-- the output of the resulting action.
375--
376-- @
377-- >>> drain $ Stream.mapM putStr $ Stream.fromList ["a", "b", "c"]
378-- abc
379--
380-- >>> :{
381-- drain $ Stream.replicateM 10 (return 1)
382-- & (fromSerial . Stream.mapM (\x -> threadDelay 1000000 >> print x))
383-- :}
384-- 1
385-- ...
386-- 1
387--
388-- > drain $ Stream.replicateM 10 (return 1)
389-- & (fromAsync . Stream.mapM (\x -> threadDelay 1000000 >> print x))
390-- @
391--
392-- /Concurrent (do not use with 'fromParallel' on infinite streams)/
393--
394-- @since 0.1.0
395{-# INLINE_EARLY mapM #-}
396mapM :: forall t m a b. (IsStream t, MonadAsync m) =>
397 (a -> m b) -> t m a -> t m b
398mapM f = fromStream . K.mapMWith (toConsK (consM @t)) f . toStream
400{-# RULES "mapM serial" mapM = mapMSerial #-}
401{-# INLINE mapMSerial #-}
402mapMSerial :: Monad m => (a -> m b) -> SerialT m a -> SerialT m b
403mapMSerial = Serial.mapM
405-- |
406-- @
407-- sequence = mapM id
408-- @
409--
410-- Replace the elements of a stream of monadic actions with the outputs of
411-- those actions.
412--
413-- @
414-- >>> drain $ Stream.sequence $ Stream.fromList [putStr "a", putStr "b", putStrLn "c"]
415-- abc
416--
417-- >>> :{
418-- drain $ Stream.replicateM 3 (return $ threadDelay 1000000 >> print 1)
419-- & (fromSerial . Stream.sequence)
420-- :}
421-- 1
422-- 1
423-- 1
424--
425-- >>> :{
426-- drain $ Stream.replicateM 3 (return $ threadDelay 1000000 >> print 1)
427-- & (fromAsync . Stream.sequence)
428-- :}
429-- 1
430-- 1
431-- 1
432--
433-- @
434--
435-- /Concurrent (do not use with 'fromParallel' on infinite streams)/
436--
437-- @since 0.1.0
438{-# INLINE sequence #-}
439sequence :: (IsStream t, MonadAsync m) => t m (m a) -> t m a
440sequence = mapM id
442------------------------------------------------------------------------------
443-- Mapping side effects
444------------------------------------------------------------------------------
446-- | Tap the data flowing through a stream into a 'Fold'. For example, you may
447-- add a tap to log the contents flowing through the stream. The fold is used
448-- only for effects, its result is discarded.
449--
450-- @
451-- Fold m a b
452-- |
453-- -----stream m a ---------------stream m a-----
454--
455-- @
456--
457-- >>> Stream.drain $ Stream.tap (Fold.drainBy print) (Stream.enumerateFromTo 1 2)
458-- 1
459-- 2
460--
461-- Compare with 'trace'.
462--
463-- @since 0.7.0
464{-# INLINE tap #-}
465tap :: (IsStream t, Monad m) => FL.Fold m a b -> t m a -> t m a
466tap f xs = fromStreamD $ D.tap f (toStreamD xs)
468-- XXX Remove this. It can be expressed in terms of Fold.sampleFromThen.
469--
470-- | @tapOffsetEvery offset n@ taps every @n@th element in the stream
471-- starting at @offset@. @offset@ can be between @0@ and @n - 1@. Offset 0
472-- means start at the first element in the stream. If the offset is outside
473-- this range then @offset `mod` n@ is used as offset.
474--
475-- >>> Stream.drain $ Stream.tapOffsetEvery 0 2 (Fold.rmapM print Fold.toList) $ Stream.enumerateFromTo 0 10
476-- [0,2,4,6,8,10]
478--
479-- /Pre-release/
480--
481{-# INLINE tapOffsetEvery #-}
482tapOffsetEvery :: (IsStream t, Monad m)
483 => Int -> Int -> FL.Fold m a b -> t m a -> t m a
484tapOffsetEvery offset n f xs =
485 fromStreamD $ D.tapOffsetEvery offset n f (toStreamD xs)
487-- | Redirect a copy of the stream to a supplied fold and run it concurrently
488-- in an independent thread. The fold may buffer some elements. The buffer size
489-- is determined by the prevailing 'maxBuffer' setting.
490--
491-- @
492-- Stream m a -> m b
493-- |
494-- -----stream m a ---------------stream m a-----
495--
496-- @
497--
498-- @
499-- >>> Stream.drain $ Stream.tapAsync (Fold.drainBy print) (Stream.enumerateFromTo 1 2)
500-- 1
501-- 2
502--
503-- @
504--
505-- Exceptions from the concurrently running fold are propagated to the current
506-- computation. Note that, because of buffering in the fold, exceptions may be
507-- delayed and may not correspond to the current element being processed in the
508-- parent stream, but we guarantee that before the parent stream stops the tap
509-- finishes and all exceptions from it are drained.
510--
511--
512-- Compare with 'tap'.
513--
514-- /Pre-release/
515{-# INLINE tapAsync #-}
516tapAsync :: (IsStream t, MonadAsync m) => FL.Fold m a b -> t m a -> t m a
517tapAsync f xs = fromStreamD $ Par.tapAsyncF f (toStreamD xs)
519-- | Redirect a copy of the stream to a supplied fold and run it concurrently
520-- in an independent thread. The fold may buffer some elements. The buffer size
521-- is determined by the prevailing 'Streamly.Prelude.maxBuffer' setting.
522--
523-- @
524-- Stream m a -> m b
525-- |
526-- -----stream m a ---------------stream m a-----
527--
528-- @
529--
530-- @
531-- > S.drain $ S.tapAsync (S.mapM_ print) (S.enumerateFromTo 1 2)
532-- 1
533-- 2
534-- @
535--
536-- Exceptions from the concurrently running fold are propagated to the current
537-- computation. Note that, because of buffering in the fold, exceptions may be
538-- delayed and may not correspond to the current element being processed in the
539-- parent stream, but we guarantee that before the parent stream stops the tap
540-- finishes and all exceptions from it are drained.
541--
542--
543-- Compare with 'tap'.
544--
545-- /Pre-release/
546{-# INLINE tapAsyncK #-}
547tapAsyncK :: (IsStream t, MonadAsync m) => (t m a -> m b) -> t m a -> t m a
548tapAsyncK f m = fromStream $ Par.tapAsyncK (f . fromStream) (toStream m)
550-- | Concurrently distribute a stream to a collection of fold functions,
551-- discarding the outputs of the folds.
552--
553-- @
554-- > Stream.drain $ Stream.distributeAsync_ [Stream.mapM_ print, Stream.mapM_ print] (Stream.enumerateFromTo 1 2)
555-- 1
556-- 2
557-- 1
558-- 2
559--
560-- @
561--
562-- @
563-- distributeAsync_ = flip (foldr tapAsync)
564-- @
565--
566-- /Pre-release/
567--
568{-# INLINE distributeAsync_ #-}
569distributeAsync_ :: (Foldable f, IsStream t, MonadAsync m)
570 => f (t m a -> m b) -> t m a -> t m a
571distributeAsync_ = flip (Prelude.foldr tapAsyncK)
573-- | @pollCounts predicate transform fold stream@ counts those elements in the
574-- stream that pass the @predicate@. The resulting count stream is sent to
575-- another thread which transforms it using @transform@ and then folds it using
576-- @fold@. The thread is automatically cleaned up if the stream stops or
577-- aborts due to exception.
578--
579-- For example, to print the count of elements processed every second:
580--
581-- @
582-- > Stream.drain $ Stream.pollCounts (const True) (Stream.rollingMap (-) . Stream.delayPost 1) (FLold.drainBy print)
583-- $ Stream.enumerateFrom 0
584-- @
585--
586-- Note: This may not work correctly on 32-bit machines.
587--
588-- /Pre-release/
589--
590{-# INLINE pollCounts #-}
591pollCounts ::
592 (IsStream t, MonadAsync m)
593 => (a -> Bool)
594 -> (t m Int -> t m Int)
595 -> Fold m Int b
596 -> t m a
597 -> t m a
598pollCounts predicate transf f xs =
599 fromStreamD
600 $ D.pollCounts predicate (toStreamD . transf . fromStreamD) f
601 $ toStreamD xs
603-- | Calls the supplied function with the number of elements consumed
604-- every @n@ seconds. The given function is run in a separate thread
605-- until the end of the stream. In case there is an exception in the
606-- stream the thread is killed during the next major GC.
607--
608-- Note: The action is not guaranteed to run if the main thread exits.
609--
610-- @
611-- > delay n = threadDelay (round $ n * 1000000) >> return n
612-- > Stream.toList $ Stream.tapRate 2 (\n -> print $ show n ++ " elements processed") (delay 1 Stream.|: delay 0.5 Stream.|: delay 0.5 Stream.|: Stream.nil)
613-- "2 elements processed"
614-- [1.0,0.5,0.5]
615-- "1 elements processed"
616-- @
617--
618-- Note: This may not work correctly on 32-bit machines.
619--
620-- /Pre-release/
621{-# INLINE tapRate #-}
622tapRate ::
623 (IsStream t, MonadAsync m, MonadCatch m)
624 => Double
625 -> (Int -> m b)
626 -> t m a
627 -> t m a
628tapRate n f xs = fromStreamD $ D.tapRate n f $ toStreamD xs
630-- | Apply a monadic function to each element flowing through the stream and
631-- discard the results.
632--
633-- @
634-- >>> Stream.drain $ Stream.trace print (Stream.enumerateFromTo 1 2)
635-- 1
636-- 2
637--
638-- @
639--
640-- Compare with 'tap'.
641--
642-- @since 0.7.0
643{-# INLINE trace #-}
644trace :: (IsStream t, MonadAsync m) => (a -> m b) -> t m a -> t m a
645trace f = mapM (\x -> void (f x) >> return x)
647-- | Perform a side effect before yielding each element of the stream and
648-- discard the results.
649--
650-- @
651-- >>> Stream.drain $ Stream.trace_ (print "got here") (Stream.enumerateFromTo 1 2)
652-- "got here"
653-- "got here"
654--
655-- @
656--
657-- Same as 'interspersePrefix_' but always serial.
658--
659-- See also: 'trace'
660--
661-- /Pre-release/
662{-# INLINE trace_ #-}
663trace_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
664trace_ eff = fromStreamD . D.mapM (\x -> eff >> return x) . toStreamD
666------------------------------------------------------------------------------
667-- Scanning with a Fold
668------------------------------------------------------------------------------
670-- | Scan a stream using the given monadic fold.
671--
672-- >>> Stream.toList $ Stream.takeWhile (< 10) $ Stream.scan Fold.sum (Stream.fromList [1..10])
673-- [0,1,3,6]
674--
675-- @since 0.7.0
676{-# INLINE scan #-}
677scan :: (IsStream t, Monad m) => Fold m a b -> t m a -> t m b
678-- scan = P.scanOnce
679scan fld m = fromStreamD $ D.scanOnce fld $ toStreamD m
681-- | Postscan a stream using the given monadic fold.
682--
683-- The following example extracts the input stream up to a point where the
684-- running average of elements is no more than 10:
685--
686-- >>> import Data.Maybe (fromJust)
687-- >>> let avg = Fold.teeWith (/) Fold.sum (fmap fromIntegral Fold.length)
688-- >>> :{
689-- Stream.toList
690-- $ Stream.map (fromJust . fst)
691-- $ Stream.takeWhile (\(_,x) -> x <= 10)
692-- $ Stream.postscan (Fold.tee Fold.last avg) (Stream.enumerateFromTo 1.0 100.0)
693-- :}
694-- [1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0,11.0,12.0,13.0,14.0,15.0,16.0,17.0,18.0,19.0]
695--
696-- @since 0.7.0
697{-# INLINE postscan #-}
698postscan :: (IsStream t, Monad m) => Fold m a b -> t m a -> t m b
699postscan fld = fromStreamD . D.postscanOnce fld . toStreamD
701------------------------------------------------------------------------------
702-- Scanning - Transformation by Folding
703------------------------------------------------------------------------------
705-- XXX It may be useful to have a version of scan where we can keep the
706-- accumulator independent of the value emitted. So that we do not necessarily
707-- have to keep a value in the accumulator which we are not using. We can pass
708-- an extraction function that will take the accumulator and the current value
709-- of the element and emit the next value in the stream. That will also make it
710-- possible to modify the accumulator after using it. In fact, the step function
711-- can return new accumulator and the value to be emitted. The signature would
712-- be more like mapAccumL. Or we can change the signature of scanx to
713-- accommodate this.
714--
715-- | Strict left scan with an extraction function. Like 'scanl'', but applies a
716-- user supplied extraction function (the third argument) at each step. This is
717-- designed to work with the @foldl@ library. The suffix @x@ is a mnemonic for
718-- extraction.
719--
720-- /Since 0.2.0/
721--
722-- /Since: 0.7.0 (Monad m constraint)/
723{-# DEPRECATED scanx "Please use scanl followed by map instead." #-}
724{-# INLINE scanx #-}
725scanx :: (IsStream t, Monad m) => (x -> a -> x) -> x -> (x -> b) -> t m a -> t m b
726scanx step begin done = fromStreamS . S.scanlx' step begin done . toStreamS
728-- XXX this needs to be concurrent
729-- XXX because of the use of D.cons for appending, scanlM' has quadratic
730-- complexity when iterated over a stream. We should use StreamK style scanlM'
731-- for linear performance on iteration.
732--
733-- | Like 'scanl'' but with a monadic step function and a monadic seed.
734--
735-- /Since: 0.4.0/
736--
737-- /Since: 0.8.0 (signature change)/
738{-# INLINE scanlM' #-}
739scanlM' :: (IsStream t, Monad m) => (b -> a -> m b) -> m b -> t m a -> t m b
740scanlM' step begin m = fromStreamD $ D.scanlM' step begin $ toStreamD m
742-- XXX because of the use of D.cons for appending, scanl' has quadratic
743-- complexity when iterated over a stream. We should use StreamK style scanlM'
744-- for linear performance on iteration.
746-- | Strict left scan. Like 'map', 'scanl'' too is a one to one transformation,
747-- however it adds an extra element.
748--
749-- @
750-- >>> Stream.toList $ Stream.scanl' (+) 0 $ fromList [1,2,3,4]
751-- [0,1,3,6,10]
752--
753-- @
754--
755-- @
756-- >>> Stream.toList $ Stream.scanl' (flip (:)) [] $ Stream.fromList [1,2,3,4]
757-- [[],[1],[2,1],[3,2,1],[4,3,2,1]]
758--
759-- @
760--
761-- The output of 'scanl'' is the initial value of the accumulator followed by
762-- all the intermediate steps and the final result of 'foldl''.
763--
764-- By streaming the accumulated state after each fold step, we can share the
765-- state across multiple stages of stream composition. Each stage can modify or
766-- extend the state, do some processing with it and emit it for the next stage,
767-- thus modularizing the stream processing. This can be useful in
768-- stateful or event-driven programming.
769--
770-- Consider the following monolithic example, computing the sum and the product
771-- of the elements in a stream in one go using a @foldl'@:
772--
773-- @
774-- >>> Stream.foldl' (\(s, p) x -> (s + x, p * x)) (0,1) $ Stream.fromList [1,2,3,4]
775-- (10,24)
776--
777-- @
778--
779-- Using @scanl'@ we can make it modular by computing the sum in the first
780-- stage and passing it down to the next stage for computing the product:
781--
782-- @
783-- >>> :{
784-- Stream.foldl' (\(_, p) (s, x) -> (s, p * x)) (0,1)
785-- $ Stream.scanl' (\(s, _) x -> (s + x, x)) (0,1)
786-- $ Stream.fromList [1,2,3,4]
787-- :}
788-- (10,24)
789--
790-- @
791--
792-- IMPORTANT: 'scanl'' evaluates the accumulator to WHNF. To avoid building
793-- lazy expressions inside the accumulator, it is recommended that a strict
794-- data structure is used for accumulator.
795--
796-- >>> scanl' step z = scan (Fold.foldl' step z)
797-- >>> scanl' f z xs = scanlM' (\a b -> return (f a b)) (return z) xs
798-- >>> scanl' f z xs = z `Stream.cons` postscanl' f z xs
799--
800-- See also: 'usingStateT'
801--
802-- @since 0.2.0
803{-# INLINE scanl' #-}
804scanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
805scanl' step z m = fromStreamS $ S.scanl' step z $ toStreamS m
807-- | Like 'scanl'' but does not stream the initial value of the accumulator.
808--
809-- >>> postscanl' step z = postscan (Fold.foldl' step z)
810-- >>> postscanl' f z = postscanlM' (\a b -> return (f a b)) (return z)
811-- >>> postscanl' f z xs = Stream.drop 1 $ Stream.scanl' f z xs
812--
813-- @since 0.7.0
814{-# INLINE postscanl' #-}
815postscanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
816postscanl' step z m = fromStreamD $ D.postscanl' step z $ toStreamD m
818-- XXX prescanl does not sound very useful, enable only if there is a
819-- compelling use case.
820--
821-- | Like scanl' but does not stream the final value of the accumulator.
822--
823-- /Pre-release/
824{-# INLINE prescanl' #-}
825prescanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
826prescanl' step z m = fromStreamD $ D.prescanl' step z $ toStreamD m
828-- XXX this needs to be concurrent
829-- | Like prescanl' but with a monadic step function and a monadic seed.
830--
831-- /Pre-release/
832{-# INLINE prescanlM' #-}
833prescanlM' :: (IsStream t, Monad m) => (b -> a -> m b) -> m b -> t m a -> t m b
834prescanlM' step z m = fromStreamD $ D.prescanlM' step z $ toStreamD m
836-- XXX this needs to be concurrent
837-- | Like 'scanl1'' but with a monadic step function.
838--
839-- @since 0.6.0
840{-# INLINE scanl1M' #-}
841scanl1M' :: (IsStream t, Monad m) => (a -> a -> m a) -> t m a -> t m a
842scanl1M' step m = fromStreamD $ D.scanl1M' step $ toStreamD m
844-- | Like 'scanl'' but for a non-empty stream. The first element of the stream
845-- is used as the initial value of the accumulator. Does nothing if the stream
846-- is empty.
847--
848-- @
849-- >>> Stream.toList $ Stream.scanl1' (+) $ fromList [1,2,3,4]
850-- [1,3,6,10]
851--
852-- @
853--
854-- @since 0.6.0
855{-# INLINE scanl1' #-}
856scanl1' :: (IsStream t, Monad m) => (a -> a -> a) -> t m a -> t m a
857scanl1' step m = fromStreamD $ D.scanl1' step $ toStreamD m
859------------------------------------------------------------------------------
860-- Filtering
861------------------------------------------------------------------------------
863-- | Modify a @t m a -> t m a@ stream transformation that accepts a predicate
864-- @(a -> b)@ to accept @((s, a) -> b)@ instead, provided a transformation @t m
865-- a -> t m (s, a)@. Convenient to filter with index or time.
866--
867-- @
868-- filterWithIndex = with indexed filter
869-- filterWithAbsTime = with timestamped filter
870-- filterWithRelTime = with timeIndexed filter
871-- @
872--
873-- /Pre-release/
874{-# INLINE with #-}
875with :: forall (t :: (Type -> Type) -> Type -> Type) m a b s. Functor (t m) =>
876 (t m a -> t m (s, a))
877 -> (((s, a) -> b) -> t m (s, a) -> t m (s, a))
878 -> (((s, a) -> b) -> t m a -> t m a)
879with f comb g = fmap snd . comb g . f
881-- | Include only those elements that pass a predicate.
882--
883-- @since 0.1.0
884{-# INLINE filter #-}
885filter :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m a
886filter p m = fromStreamS $ S.filter p $ toStreamS m
888-- | Same as 'filter' but with a monadic predicate.
889--
890-- @since 0.4.0
891{-# INLINE filterM #-}
892filterM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
893filterM p m = fromStreamD $ D.filterM p $ toStreamD m
895-- | Drop repeated elements that are adjacent to each other using the supplied
896-- comparison function.
897--
898-- @uniq = uniqBy (==)
899--
900-- To strip duplicate path separators:
901--
902-- @
903-- f x y = x == '/' && x == y
904-- Stream.toList $ Stream.uniqBy f $ Stream.fromList "//a//b"
905-- "/a/b"
906-- @
907--
908-- Space: @O(1)@
909--
910-- See also: 'nubBy'.
911--
912-- /Pre-release/
913--
914{-# INLINE uniqBy #-}
915uniqBy :: (IsStream t, Monad m, Functor (t m)) =>
916 (a -> a -> Bool) -> t m a -> t m a
917uniqBy eq = catMaybes . rollingMap f
919 where
921 f pre curr =
922 case pre of
923 Nothing -> Just curr
924 Just x -> if x `eq` curr then Nothing else Just curr
926-- | Drop repeated elements that are adjacent to each other.
927--
928-- @since 0.6.0
929{-# INLINE uniq #-}
930uniq :: (Eq a, IsStream t, Monad m) => t m a -> t m a
931uniq = fromStreamD . D.uniq . toStreamD
933-- | Strip all leading and trailing occurrences of an element passing a
934-- predicate and make all other consecutive occurrences uniq.
935--
936-- @
937-- prune p = dropWhileAround p $ uniqBy (x y -> p x && p y)
938-- @
939--
940-- @
941-- > Stream.prune isSpace (Stream.fromList " hello world! ")
942-- "hello world!"
943--
944-- @
945--
946-- Space: @O(1)@
947--
948-- /Unimplemented/
949{-# INLINE prune #-}
950prune ::
951 -- (IsStream t, Monad m, Eq a) =>
952 (a -> Bool) -> t m a -> t m a
953prune = error "Not implemented yet!"
955-- Possible implementation:
956-- @repeated =
957-- Stream.catMaybes . Stream.parseMany (Parser.groupBy (==) Fold.repeated)@
958--
959-- 'Fold.repeated' should return 'Just' when repeated, and 'Nothing' for a
960-- single element.
961--
962-- | Emit only repeated elements, once.
963--
964-- /Unimplemented/
965repeated :: -- (IsStream t, Monad m, Eq a) =>
966 t m a -> t m a
967repeated = undefined
969-- We can have more efficient implementations for nubOrd and nubInt by using
970-- Set and IntSet to find/remove duplication. For Hashable we can use a
971-- hashmap. Use rewrite rules to specialize to more efficient impls.
972--
973-- | Drop repeated elements anywhere in the stream.
974--
975-- /Caution: not scalable for infinite streams/
976--
977-- /See also: nubWindowBy/
978--
979-- /Unimplemented/
980--
981{-# INLINE nubBy #-}
982nubBy :: -- (IsStream t, Monad m) =>
983 (a -> a -> Bool) -> t m a -> t m a
984nubBy = undefined -- fromStreamD . D.nubBy . toStreamD
986-- | Drop repeated elements within the specified tumbling window in the stream.
987--
988-- @nubBy = nubWindowBy maxBound@
989--
990-- /Unimplemented/
991--
992{-# INLINE nubWindowBy #-}
993nubWindowBy :: -- (IsStream t, Monad m) =>
994 Int -> (a -> a -> Bool) -> t m a -> t m a
995nubWindowBy = undefined -- fromStreamD . D.nubWithinBy . toStreamD
997-- | Deletes the first occurrence of the element in the stream that satisfies
998-- the given equality predicate.
999--
1000-- @
1001-- >>> Stream.toList $ Stream.deleteBy (==) 3 $ Stream.fromList [1,3,3,5]
1002-- [1,3,5]
1004-- @
1006-- @since 0.6.0
1007{-# INLINE deleteBy #-}
1008deleteBy :: (IsStream t, Monad m) => (a -> a -> Bool) -> a -> t m a -> t m a
1009deleteBy cmp x m = fromStreamS $ S.deleteBy cmp x (toStreamS m)
1011------------------------------------------------------------------------------
1012-- Lossy Buffering
1013------------------------------------------------------------------------------
1015-- XXX We could use 'maxBuffer Block/Drop/Rotate/Sample' instead. However we
1016-- may want to have the evaluation rate independent of the sampling rate. To
1017-- support that we can decouple evaluation and sampling in independent stages.
1018-- The sampling stage would strictly evaluate and sample, the evaluation stage
1019-- would control the evaluation rate.
1021-- | Evaluate the input stream continuously and keep only the oldest @n@
1022-- elements in the buffer, discard the new ones when the buffer is full. When
1023-- the output stream is evaluated it consumes the values from the buffer in a
1024-- FIFO manner.
1026-- /Unimplemented/
1028{-# INLINE sampleOld #-}
1029sampleOld :: -- (IsStream t, Monad m) =>
1030 Int -> t m a -> t m a
1031sampleOld = undefined
1033-- | Evaluate the input stream continuously and keep only the latest @n@
1034-- elements in a ring buffer, keep discarding the older ones to make space for
1035-- the new ones. When the output stream is evaluated it consumes the values
1036-- from the buffer in a FIFO manner.
1038-- /Unimplemented/
1040{-# INLINE sampleNew #-}
1041sampleNew :: -- (IsStream t, Monad m) =>
1042 Int -> t m a -> t m a
1043sampleNew = undefined
1045-- | Like 'sampleNew' but samples at uniform intervals to match the consumer
1046-- rate. Note that 'sampleNew' leads to non-uniform sampling depending on the
1047-- consumer pattern.
1049-- /Unimplemented/
1051{-# INLINE sampleRate #-}
1052sampleRate :: -- (IsStream t, Monad m) =>
1053 Double -> t m a -> t m a
1054sampleRate = undefined
1056------------------------------------------------------------------------------
1057-- Trimming
1058------------------------------------------------------------------------------
1060-- | Same as 'takeWhile' but with a monadic predicate.
1062-- @since 0.4.0
1063{-# INLINE takeWhileM #-}
1064takeWhileM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
1065takeWhileM p m = fromStreamD $ D.takeWhileM p $ toStreamD m
1067-- See the lastN fold for impl hints. Use a Data.Array based ring buffer.
1069-- takeLast n = Stream.concatM . fmap Array.toStream . fold Fold.lastN
1071-- | Take @n@ elements at the end of the stream.
1073-- O(n) space, where n is the number elements taken.
1075-- /Unimplemented/
1076{-# INLINE takeLast #-}
1077takeLast :: -- (IsStream t, Monad m) =>
1078 Int -> t m a -> t m a
1079takeLast = undefined -- fromStreamD $ D.takeLast n $ toStreamD m
1081-- | Take time interval @i@ seconds at the end of the stream.
1083-- O(n) space, where n is the number elements taken.
1085-- /Unimplemented/
1086{-# INLINE takeLastInterval #-}
1087takeLastInterval :: -- (IsStream t, Monad m) =>
1088 Double -> t m a -> t m a
1089takeLastInterval = undefined -- fromStreamD $ D.takeLast n $ toStreamD m
1091-- | Take all consecutive elements at the end of the stream for which the
1092-- predicate is true.
1094-- O(n) space, where n is the number elements taken.
1096-- /Unimplemented/
1097{-# INLINE takeWhileLast #-}
1098takeWhileLast :: -- (IsStream t, Monad m) =>
1099 (a -> Bool) -> t m a -> t m a
1100takeWhileLast = undefined -- fromStreamD $ D.takeWhileLast n $ toStreamD m
1102-- | Like 'takeWhile' and 'takeWhileLast' combined.
1104-- O(n) space, where n is the number elements taken from the end.
1106-- /Unimplemented/
1107{-# INLINE takeWhileAround #-}
1108takeWhileAround :: -- (IsStream t, Monad m) =>
1109 (a -> Bool) -> t m a -> t m a
1110takeWhileAround = undefined -- fromStreamD $ D.takeWhileAround n $ toStreamD m
1112-- | @takeInterval duration@ yields stream elements upto specified time
1113-- @duration@. The duration starts when the stream is evaluated for the first
1114-- time, before the first element is yielded. The time duration is checked
1115-- before generating each element, if the duration has expired the stream
1116-- stops.
1118-- The total time taken in executing the stream is guaranteed to be /at least/
1119-- @duration@, however, because the duration is checked before generating an
1120-- element, the upper bound is indeterminate and depends on the time taken in
1121-- generating and processing the last element.
1123-- No element is yielded if the duration is zero. At least one element is
1124-- yielded if the duration is non-zero.
1126-- /Pre-release/
1128{-# INLINE takeInterval #-}
1129takeInterval ::(MonadIO m, IsStream t, TimeUnit64 d) => d -> t m a -> t m a
1130takeInterval d = fromStreamD . D.takeByTime d . toStreamD
1132-- | Drop elements in the stream as long as the predicate succeeds and then
1133-- take the rest of the stream.
1135-- @since 0.1.0
1136{-# INLINE dropWhile #-}
1137dropWhile :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m a
1138dropWhile p m = fromStreamS $ S.dropWhile p $ toStreamS m
1140-- | Same as 'dropWhile' but with a monadic predicate.
1142-- @since 0.4.0
1143{-# INLINE dropWhileM #-}
1144dropWhileM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
1145dropWhileM p m = fromStreamD $ D.dropWhileM p $ toStreamD m
1147-- | @dropInterval duration@ drops stream elements until specified @duration@ has
1148-- passed. The duration begins when the stream is evaluated for the first
1149-- time. The time duration is checked /after/ generating a stream element, the
1150-- element is yielded if the duration has expired otherwise it is dropped.
1152-- The time elapsed before starting to generate the first element is /at most/
1153-- @duration@, however, because the duration expiry is checked after the
1154-- element is generated, the lower bound is indeterminate and depends on the
1155-- time taken in generating an element.
1157-- All elements are yielded if the duration is zero.
1159-- /Pre-release/
1161{-# INLINE dropInterval #-}
1162dropInterval ::(MonadIO m, IsStream t, TimeUnit64 d) => d -> t m a -> t m a
1163dropInterval d = fromStreamD . D.dropByTime d . toStreamD
1165-- | Drop @n@ elements at the end of the stream.
1167-- O(n) space, where n is the number elements dropped.
1169-- /Unimplemented/
1170{-# INLINE dropLast #-}
1171dropLast :: -- (IsStream t, Monad m) =>
1172 Int -> t m a -> t m a
1173dropLast = undefined -- fromStreamD $ D.dropLast n $ toStreamD m
1175-- | Drop time interval @i@ seconds at the end of the stream.
1177-- O(n) space, where n is the number elements dropped.
1179-- /Unimplemented/
1180{-# INLINE dropLastInterval #-}
1181dropLastInterval :: -- (IsStream t, Monad m) =>
1182 Int -> t m a -> t m a
1183dropLastInterval = undefined
1185-- | Drop all consecutive elements at the end of the stream for which the
1186-- predicate is true.
1188-- O(n) space, where n is the number elements dropped.
1190-- /Unimplemented/
1191{-# INLINE dropWhileLast #-}
1192dropWhileLast :: -- (IsStream t, Monad m) =>
1193 (a -> Bool) -> t m a -> t m a
1194dropWhileLast = undefined -- fromStreamD $ D.dropWhileLast n $ toStreamD m
1196-- | Like 'dropWhile' and 'dropWhileLast' combined.
1198-- O(n) space, where n is the number elements dropped from the end.
1200-- /Unimplemented/
1201{-# INLINE dropWhileAround #-}
1202dropWhileAround :: -- (IsStream t, Monad m) =>
1203 (a -> Bool) -> t m a -> t m a
1204dropWhileAround = undefined -- fromStreamD $ D.dropWhileAround n $ toStreamD m
1206------------------------------------------------------------------------------
1207-- Inserting Elements
1208------------------------------------------------------------------------------
1210-- | @insertBy cmp elem stream@ inserts @elem@ before the first element in
1211-- @stream@ that is less than @elem@ when compared using @cmp@.
1213-- @
1214-- insertBy cmp x = 'mergeBy' cmp ('fromPure' x)
1215-- @
1217-- @
1218-- >>> Stream.toList $ Stream.insertBy compare 2 $ Stream.fromList [1,3,5]
1219-- [1,2,3,5]
1221-- @
1223-- @since 0.6.0
1224{-# INLINE insertBy #-}
1225insertBy ::
1226 (IsStream t, Monad m) => (a -> a -> Ordering) -> a -> t m a -> t m a
1227insertBy cmp x m = fromStreamS $ S.insertBy cmp x (toStreamS m)
1229-- | Insert a pure value between successive elements of a stream.
1231-- >>> Stream.toList $ Stream.intersperse ',' $ Stream.fromList "hello"
1232-- "h,e,l,l,o"
1234-- @since 0.7.0
1235{-# INLINE intersperse #-}
1236intersperse :: (IsStream t, MonadAsync m) => a -> t m a -> t m a
1237intersperse a = fromStreamS . S.intersperse a . toStreamS
1239-- | Insert a side effect before consuming an element of a stream except the
1240-- first one.
1242-- >>> Stream.drain $ Stream.trace putChar $ Stream.intersperseM_ (putChar '.') $ Stream.fromList "hello"
1243-- h.e.l.l.o
1245-- /Pre-release/
1246{-# INLINE intersperseM_ #-}
1247intersperseM_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
1248intersperseM_ m = fromStreamD . D.intersperseM_ m . toStreamD
1250-- | Intersperse a monadic action into the input stream after every @n@
1251-- elements.
1253-- @
1254-- > Stream.toList $ Stream.intersperseBySpan 2 (return ',') $ Stream.fromList "hello"
1255-- "he,ll,o"
1257-- @
1259-- /Unimplemented/
1260{-# INLINE intersperseBySpan #-}
1261intersperseBySpan :: -- IsStream t =>
1262 Int -> m a -> t m a -> t m a
1263intersperseBySpan _n _f _xs = undefined
1265-- | Insert an effect and its output after consuming an element of a stream.
1267-- >>> Stream.toList $ Stream.trace putChar $ intersperseSuffix (putChar '.' >> return ',') $ Stream.fromList "hello"
1268-- h.,e.,l.,l.,o.,"h,e,l,l,o,"
1270-- /Pre-release/
1271{-# INLINE intersperseSuffix #-}
1272intersperseSuffix :: (IsStream t, Monad m) => m a -> t m a -> t m a
1273intersperseSuffix m = fromStreamD . D.intersperseSuffix m . toStreamD
1275-- | Insert a side effect after consuming an element of a stream.
1277-- @
1278-- >>> Stream.mapM_ putChar $ Stream.intersperseSuffix_ (threadDelay 1000000) $ Stream.fromList "hello"
1279-- hello
1281-- @
1283-- /Pre-release/
1285{-# INLINE intersperseSuffix_ #-}
1286intersperseSuffix_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
1287intersperseSuffix_ m = fromStreamD . D.intersperseSuffix_ m . toStreamD
1289-- XXX Use an offset argument, like tapOffsetEvery
1291-- | Like 'intersperseSuffix' but intersperses an effectful action into the
1292-- input stream after every @n@ elements and after the last element.
1294-- >>> Stream.toList $ Stream.intersperseSuffixBySpan 2 (return ',') $ Stream.fromList "hello"
1295-- "he,ll,o,"
1297-- /Pre-release/
1299{-# INLINE intersperseSuffixBySpan #-}
1300intersperseSuffixBySpan :: (IsStream t, Monad m)
1301 => Int -> m a -> t m a -> t m a
1302intersperseSuffixBySpan n eff =
1303 fromStreamD . D.intersperseSuffixBySpan n eff . toStreamD
1305-- | Insert a side effect before consuming an element of a stream.
1307-- >>> Stream.toList $ Stream.trace putChar $ Stream.interspersePrefix_ (putChar '.' >> return ',') $ Stream.fromList "hello"
1308-- .h.e.l.l.o"hello"
1310-- Same as 'trace_' but may be concurrent.
1312-- /Concurrent/
1314-- /Pre-release/
1316{-# INLINE interspersePrefix_ #-}
1317interspersePrefix_ :: (IsStream t, MonadAsync m) => m b -> t m a -> t m a
1318interspersePrefix_ m = mapM (\x -> void m >> return x)
1320------------------------------------------------------------------------------
1321-- Inserting Time
1322------------------------------------------------------------------------------
1324-- Note: delay must be serial.
1326-- | Introduce a delay of specified seconds before consuming an element of the
1327-- stream except the first one.
1329-- >>> Stream.mapM_ print $ Stream.timestamped $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
1330-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),1)
1331-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),2)
1332-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),3)
1334-- @since 0.8.0
1336{-# INLINE delay #-}
1337delay :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
1338delay n = intersperseM_ $ liftIO $ threadDelay $ round $ n * 1000000
1340-- Note: delay must be serial.
1342-- | Introduce a delay of specified seconds after consuming an element of a
1343-- stream.
1345-- >>> Stream.mapM_ print $ Stream.timestamped $ Stream.delayPost 1 $ Stream.enumerateFromTo 1 3
1346-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),1)
1347-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),2)
1348-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),3)
1350-- /Pre-release/
1352{-# INLINE delayPost #-}
1353delayPost :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
1354delayPost n = intersperseSuffix_ $ liftIO $ threadDelay $ round $ n * 1000000
1356-- Note: delay must be serial, that's why 'trace_' is used.
1358-- | Introduce a delay of specified seconds before consuming an element of a
1359-- stream.
1361-- >>> Stream.mapM_ print $ Stream.timestamped $ Stream.delayPre 1 $ Stream.enumerateFromTo 1 3
1362-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),1)
1363-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),2)
1364-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),3)
1366-- /Pre-release/
1368{-# INLINE delayPre #-}
1369delayPre :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
1370delayPre n = trace_ $ liftIO $ threadDelay $ round $ n * 1000000
1372------------------------------------------------------------------------------
1373-- Reorder in sequence
1374------------------------------------------------------------------------------
1376-- | Buffer until the next element in sequence arrives. The function argument
1377-- determines the difference in sequence numbers. This could be useful in
1378-- implementing sequenced streams, for example, TCP reassembly.
1380-- /Unimplemented/
1382{-# INLINE reassembleBy #-}
1383reassembleBy
1384 :: -- (IsStream t, Monad m) =>
1385 Fold m a b
1386 -> (a -> a -> Int)
1387 -> t m a
1388 -> t m b
1389reassembleBy = undefined
1391------------------------------------------------------------------------------
1392-- Position Indexing
1393------------------------------------------------------------------------------
1395-- |
1396-- > indexed = Stream.postscanl' (\(i, _) x -> (i + 1, x)) (-1,undefined)
1397-- > indexed = Stream.zipWith (,) (Stream.enumerateFrom 0)
1399-- Pair each element in a stream with its index, starting from index 0.
1401-- >>> Stream.toList $ Stream.indexed $ Stream.fromList "hello"
1402-- [(0,'h'),(1,'e'),(2,'l'),(3,'l'),(4,'o')]
1404-- @since 0.6.0
1405{-# INLINE indexed #-}
1406indexed :: (IsStream t, Monad m) => t m a -> t m (Int, a)
1407indexed = fromStreamD . D.indexed . toStreamD
1409-- |
1410-- > indexedR n = Stream.postscanl' (\(i, _) x -> (i - 1, x)) (n + 1,undefined)
1411-- > indexedR n = Stream.zipWith (,) (Stream.enumerateFromThen n (n - 1))
1413-- Pair each element in a stream with its index, starting from the
1414-- given index @n@ and counting down.
1416-- >>> Stream.toList $ Stream.indexedR 10 $ Stream.fromList "hello"
1417-- [(10,'h'),(9,'e'),(8,'l'),(7,'l'),(6,'o')]
1419-- @since 0.6.0
1420{-# INLINE indexedR #-}
1421indexedR :: (IsStream t, Monad m) => Int -> t m a -> t m (Int, a)
1422indexedR n = fromStreamD . D.indexedR n . toStreamD
1424-------------------------------------------------------------------------------
1425-- Time Indexing
1426-------------------------------------------------------------------------------
1428-- Note: The timestamp stream must be the second stream in the zip so that the
1429-- timestamp is generated after generating the stream element and not before.
1430-- If we do not do that then the following example will generate the same
1431-- timestamp for first two elements:
1433-- Stream.mapM_ print $ Stream.timestamped $ Stream.delay $ Stream.enumerateFromTo 1 3
1435-- | Pair each element in a stream with an absolute timestamp, using a clock of
1436-- specified granularity. The timestamp is generated just before the element
1437-- is consumed.
1439-- >>> Stream.mapM_ print $ Stream.timestampWith 0.01 $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
1440-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),1)
1441-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),2)
1442-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),3)
1444-- /Pre-release/
1446{-# INLINE timestampWith #-}
1447timestampWith :: (IsStream t, MonadAsync m, Functor (t m))
1448 => Double -> t m a -> t m (AbsTime, a)
1449timestampWith g stream = zipWith (flip (,)) stream (absTimesWith g)
1451-- TBD: check performance vs a custom implementation without using zipWith.
1453-- /Pre-release/
1455{-# INLINE timestamped #-}
1456timestamped :: (IsStream t, MonadAsync m, Functor (t m))
1457 => t m a -> t m (AbsTime, a)
1458timestamped = timestampWith 0.01
1460-- | Pair each element in a stream with relative times starting from 0, using a
1461-- clock with the specified granularity. The time is measured just before the
1462-- element is consumed.
1464-- >>> Stream.mapM_ print $ Stream.timeIndexWith 0.01 $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
1465-- (RelTime64 (NanoSecond64 ...),1)
1466-- (RelTime64 (NanoSecond64 ...),2)
1467-- (RelTime64 (NanoSecond64 ...),3)
1469-- /Pre-release/
1471{-# INLINE timeIndexWith #-}
1472timeIndexWith :: (IsStream t, MonadAsync m, Functor (t m))
1473 => Double -> t m a -> t m (RelTime64, a)
1474timeIndexWith g stream = zipWith (flip (,)) stream (relTimesWith g)
1476-- | Pair each element in a stream with relative times starting from 0, using a
1477-- 10 ms granularity clock. The time is measured just before the element is
1478-- consumed.
1480-- >>> Stream.mapM_ print $ Stream.timeIndexed $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
1481-- (RelTime64 (NanoSecond64 ...),1)
1482-- (RelTime64 (NanoSecond64 ...),2)
1483-- (RelTime64 (NanoSecond64 ...),3)
1485-- /Pre-release/
1487{-# INLINE timeIndexed #-}
1488timeIndexed :: (IsStream t, MonadAsync m, Functor (t m))
1489 => t m a -> t m (RelTime64, a)
1490timeIndexed = timeIndexWith 0.01
1492------------------------------------------------------------------------------
1493-- Searching
1494------------------------------------------------------------------------------
1496-- | Find all the indices where the value of the element in the stream is equal
1497-- to the given value.
1499-- > elemIndices a = findIndices (== a)
1501-- @since 0.5.0
1502{-# INLINE elemIndices #-}
1503elemIndices :: (IsStream t, Eq a, Monad m) => a -> t m a -> t m Int
1504elemIndices a = findIndices (== a)
1506------------------------------------------------------------------------------
1507-- Rolling map
1508------------------------------------------------------------------------------
1510-- XXX this is not a one-to-one map so calling it map may not be right.
1511-- We can perhaps call it zipWithTail or rollWith.
1513-- | Apply a function on every two successive elements of a stream. The first
1514-- argument of the map function is the previous element and the second argument
1515-- is the current element. When the current element is the first element, the
1516-- previous element is 'Nothing'.
1518-- /Pre-release/
1520{-# INLINE rollingMap #-}
1521rollingMap :: (IsStream t, Monad m) => (Maybe a -> a -> b) -> t m a -> t m b
1522rollingMap f m = fromStreamD $ D.rollingMap f $ toStreamD m
1524-- | Like 'rollingMap' but with an effectful map function.
1526-- /Pre-release/
1528{-# INLINE rollingMapM #-}
1529rollingMapM :: (IsStream t, Monad m) => (Maybe a -> a -> m b) -> t m a -> t m b
1530rollingMapM f m = fromStreamD $ D.rollingMapM f $ toStreamD m
1532-- | Like 'rollingMap' but requires at least two elements in the stream,
1533-- returns an empty stream otherwise.
1535-- This is the stream equivalent of the list idiom @zipWith f xs (tail xs)@.
1537-- /Pre-release/
1539{-# INLINE rollingMap2 #-}
1540rollingMap2 :: (IsStream t, Monad m) => (a -> a -> b) -> t m a -> t m b
1541rollingMap2 f m = fromStreamD $ D.rollingMap2 f $ toStreamD m
1543------------------------------------------------------------------------------
1544-- Maybe Streams
1545------------------------------------------------------------------------------
1547-- | Map a 'Maybe' returning function to a stream, filter out the 'Nothing'
1548-- elements, and return a stream of values extracted from 'Just'.
1550-- Equivalent to:
1552-- @
1553-- mapMaybe f = Stream.map 'fromJust' . Stream.filter 'isJust' . Stream.map f
1554-- @
1556-- @since 0.3.0
1557{-# INLINE mapMaybe #-}
1558mapMaybe :: (IsStream t, Monad m) => (a -> Maybe b) -> t m a -> t m b
1559mapMaybe f m = fromStreamS $ S.mapMaybe f $ toStreamS m
1561-- | Like 'mapMaybe' but maps a monadic function.
1563-- Equivalent to:
1565-- @
1566-- mapMaybeM f = Stream.map 'fromJust' . Stream.filter 'isJust' . Stream.mapM f
1567-- @
1569-- /Concurrent (do not use with 'fromParallel' on infinite streams)/
1571-- @since 0.3.0
1572{-# INLINE_EARLY mapMaybeM #-}
1573mapMaybeM :: (IsStream t, MonadAsync m, Functor (t m))
1574 => (a -> m (Maybe b)) -> t m a -> t m b
1575mapMaybeM f = fmap fromJust . filter isJust . mapM f
1577{-# RULES "mapMaybeM serial" mapMaybeM = mapMaybeMSerial #-}
1578{-# INLINE mapMaybeMSerial #-}
1579mapMaybeMSerial :: Monad m => (a -> m (Maybe b)) -> SerialT m a -> SerialT m b
1580mapMaybeMSerial f m = fromStreamD $ D.mapMaybeM f $ toStreamD m
1582-- | In a stream of 'Maybe's, discard 'Nothing's and unwrap 'Just's.
1584-- /Pre-release/
1586{-# INLINE catMaybes #-}
1587catMaybes :: (IsStream t, Monad m, Functor (t m)) => t m (Maybe a) -> t m a
1588catMaybes = fmap fromJust . filter isJust
1590------------------------------------------------------------------------------
1591-- Either streams
1592------------------------------------------------------------------------------
1594-- | Discard 'Right's and unwrap 'Left's in an 'Either' stream.
1596-- /Pre-release/
1598{-# INLINE lefts #-}
1599lefts :: (IsStream t, Monad m, Functor (t m)) => t m (Either a b) -> t m a
1600lefts = fmap (fromLeft undefined) . filter isLeft
1602-- | Discard 'Left's and unwrap 'Right's in an 'Either' stream.
1604-- /Pre-release/
1606{-# INLINE rights #-}
1607rights :: (IsStream t, Monad m, Functor (t m)) => t m (Either a b) -> t m b
1608rights = fmap (fromRight undefined) . filter isRight
1610-- | Remove the either wrapper and flatten both lefts and as well as rights in
1611-- the output stream.
1613-- /Pre-release/
1615{-# INLINE both #-}
1616both :: Functor (t m) => t m (Either a a) -> t m a
1617both = fmap (either id id)
1619------------------------------------------------------------------------------
1620-- Concurrent Application
1621------------------------------------------------------------------------------
1623-- | Parallel transform application operator; applies a stream transformation
1624-- function @t m a -> t m b@ to a stream @t m a@ concurrently; the input stream
1625-- is evaluated asynchronously in an independent thread yielding elements to a
1626-- buffer and the transformation function runs in another thread consuming the
1627-- input from the buffer. '|$' is just like regular function application
1628-- operator '$' except that it is concurrent.
1630-- If you read the signature as @(t m a -> t m b) -> (t m a -> t m b)@ you can
1631-- look at it as a transformation that converts a transform function to a
1632-- buffered concurrent transform function.
1634-- The following code prints a value every second even though each stage adds a
1635-- 1 second delay.
1638-- >>> :{
1639-- Stream.drain $
1640-- Stream.mapM (\x -> threadDelay 1000000 >> print x)
1641-- |$ Stream.replicateM 3 (threadDelay 1000000 >> return 1)
1642-- :}
1643-- 1
1644-- 1
1645-- 1
1647-- /Concurrent/
1649-- /Since: 0.3.0 ("Streamly")/
1651-- @since 0.8.0
1652{-# INLINE (|$) #-}
1653(|$) :: (IsStream t, MonadAsync m) => (t m a -> t m b) -> (t m a -> t m b)
1654-- (|$) f = f . mkAsync
1655(|$) f = f . mkParallel
1657infixr 0 |$
1659-- | Same as '|$'.
1661-- /Internal/
1663{-# INLINE applyAsync #-}
1664applyAsync :: (IsStream t, MonadAsync m)
1665 => (t m a -> t m b) -> (t m a -> t m b)
1666applyAsync = (|$)
1668-- | Same as '|$' but with arguments reversed.
1670-- (|&) = flip (|$)
1672-- /Concurrent/
1674-- /Since: 0.3.0 ("Streamly")/
1676-- @since 0.8.0
1677{-# INLINE (|&) #-}
1678(|&) :: (IsStream t, MonadAsync m) => t m a -> (t m a -> t m b) -> t m b
1679x |& f = f |$ x
1681infixl 1 |&