on e95e149 help sign in
1537 lines 49 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 , foldrT
19 -- * Mapping
20 -- | Stateless one-to-one maps.
21 , Serial.map
22 , sequence
23 , mapM
24 , smapM
26 -- * Mapping Side Effects (Observation)
27 -- | See also the intersperse*_ combinators.
28 , trace
29 , trace_
30 , tap
31 , tapOffsetEvery
32 , tapAsync
33 , tapRate
34 , pollCounts
36 -- * Scanning By 'Fold'
37 , scan
38 , postscan
40 -- * Scanning
41 -- | Left scans. Stateful, mostly one-to-one maps.
42 , scanl'
43 , scanlM'
44 , scanlMAfter'
45 , postscanl'
46 , postscanlM'
47 , prescanl'
48 , prescanlM'
49 , scanl1'
50 , scanl1M'
52 -- XXX Once we have pipes the contravariant transformations can be
53 -- represented by attaching pipes before a transformation.
54 --
55 -- , lscanl'
56 -- , lscanlM'
57 -- , lscanl1'
58 -- , lscanl1M'
59 --
60 -- , lpostscanl'
61 -- , lpostscanlM'
62 -- , lprescanl'
63 -- , lprescanlM'
65 -- * Filtering
66 -- | Produce a subset of the stream using criteria based on the values of
67 -- the elements. We can use a concatMap and scan for filtering but these
68 -- combinators are more efficient and convenient.
70 , with
71 , deleteBy
72 , filter
73 , filterM
74 , uniq
75 , uniqBy
76 , nubBy
77 , nubWindowBy
78 , prune
79 , repeated
81 -- * Trimming
82 -- | Produce a subset of the stream trimmed at ends.
84 , take
85 , takeInterval
86 , takeLast
87 , takeLastInterval
88 , takeWhile
89 , takeWhileM
90 , takeWhileLast
91 , takeWhileAround
92 , drop
93 , dropInterval
94 , dropLast
95 , dropLastInterval
96 , dropWhile
97 , dropWhileM
98 , dropWhileLast
99 , dropWhileAround
101 -- * Inserting Elements
102 -- | Produce a superset of the stream. This is the opposite of
103 -- filtering/sampling. We can always use concatMap and scan for inserting
104 -- but these combinators are more efficient and convenient.
106 -- Element agnostic (Opposite of sampling)
107 , intersperse
108 , intersperseM -- XXX naming
109 , intersperseBySpan
111 , intersperseSuffix
112 , intersperseSuffixBySpan
113 , interjectSuffix
115 -- , interspersePrefix
116 -- , interspersePrefixBySpan
118 -- * Inserting Side Effects/Time
119 , intersperseM_ -- XXX naming
120 , delay
121 , intersperseSuffix_
122 , delayPost
123 , interspersePrefix_
124 , delayPre
126 -- * Element Aware Insertion
127 -- | Opposite of filtering
128 , insertBy
129 -- , intersperseByBefore
130 -- , intersperseByAfter
132 -- * Reordering
133 , reverse
134 , reverse'
135 , reassembleBy
137 -- * Position Indexing
138 , indexed
139 , indexedR
141 -- * Time Indexing
142 , timestamped
143 , timestampWith
144 -- , timestampedR -- timer
145 , timeIndexed
146 , timeIndexWith
148 -- * Searching
149 , findIndices -- XXX indicesBy
150 , elemIndices -- XXX indicesOf
152 -- * Rolling map
153 -- | Map using the previous element.
154 , rollingMapM
155 , rollingMap
157 -- * Maybe Streams
158 -- Move these to Streamly.Data.Maybe.Stream?
159 , catMaybes -- XXX justs (like lefts/rights)
160 , mapMaybe
161 , mapMaybeM
163 -- * Either Streams
164 -- Move these to Streamly.Data.Either.Stream?
165 , lefts
166 , rights
168 -- * Concurrent Evaluation
169 -- ** Concurrent Pipelines
170 -- | Run streaming stages concurrently.
172 , Par.mkParallel
173 , applyAsync
174 , (|$)
175 , (|&)
177 -- ** Concurrency Control
178 , maxThreads
180 -- ** Buffering and Sampling
181 -- | Evaluate strictly using a buffer of results. When the buffer becomes
182 -- full we can block, drop the new elements, drop the oldest element and
183 -- insert the new at the end or keep dropping elements uniformly to match
184 -- the rate of the consumer.
185 , maxBuffer
186 , sampleOld
187 , sampleNew
188 , sampleRate
190 -- ** Rate Limiting
191 -- | Evaluate the stream at uniform intervals to maintain a specified
192 -- evaluation rate.
193 , Rate (..)
194 , rate
195 , avgRate
196 , minRate
197 , maxRate
198 , constRate
200 -- * Diagnostics
201 , inspectMode
203 -- * Deprecated
204 , scanx
205 )
206where
208#include "inline.hs"
210import Control.Concurrent (threadDelay)
211import Control.Monad (void)
212import Control.Monad.Catch (MonadCatch)
213import Control.Monad.IO.Class (MonadIO(..))
214import Control.Monad.Trans.Class (MonadTrans(..))
215import Data.Either (isLeft, isRight)
216import Data.Kind (Type)
217import Data.Maybe (isJust, fromJust)
218import Streamly.Internal.BaseCompat (fromLeft, fromRight)
219import Streamly.Internal.Data.Fold.Type (Fold (..))
220import Streamly.Internal.Data.Pipe.Type (Pipe (..))
221import Streamly.Internal.Data.Stream.IsStream.Combinators
222 ( inspectMode, maxBuffer, maxThreads, rate, avgRate, minRate
223 , maxRate, constRate)
224import Streamly.Internal.Data.Stream.IsStream.Common
225 ( absTimesWith
226 , drop
227 , findIndices
228 , postscanlM'
229 , relTimesWith
230 , reverse
231 , reverse'
232 , scanlMAfter'
233 , smapM
234 , take
235 , takeWhile
236 , interjectSuffix
237 , intersperseM
238 )
239import Streamly.Internal.Data.Stream.Prelude (fromStreamS, toStreamS)
240import Streamly.Internal.Data.Stream.Serial (SerialT)
241import Streamly.Internal.Data.Stream.StreamD (fromStreamD, toStreamD)
242import Streamly.Internal.Data.Stream.StreamK (IsStream)
243import Streamly.Internal.Data.SVar (MonadAsync, Rate(..))
244import Streamly.Internal.Data.Time.Units (TimeUnit64, AbsTime, RelTime64)
246import qualified Streamly.Internal.Data.Fold as FL
247import qualified Streamly.Internal.Data.Stream.Parallel as Par
248import qualified Streamly.Internal.Data.Stream.Prelude as P
249import qualified Streamly.Internal.Data.Stream.Serial as Serial
250import qualified Streamly.Internal.Data.Stream.StreamD as D
251import qualified Streamly.Internal.Data.Stream.StreamK as K
252import qualified Streamly.Internal.Data.Stream.Zip as Z
253#ifdef USE_STREAMK_ONLY
254import qualified Streamly.Internal.Data.Stream.StreamK as S
255#else
256import qualified Streamly.Internal.Data.Stream.StreamD as S
257#endif
259import Prelude hiding
260 ( filter, drop, dropWhile, take, takeWhile, foldr, map, mapM, sequence
261 , reverse, foldr1 , scanl, scanl1)
263--
264-- $setup
265-- >>> :m
266-- >>> import Prelude hiding ( filter, drop, dropWhile, take, takeWhile, foldr, map, mapM, sequence, reverse, foldr1 , scanl, scanl1)
267-- >>> import qualified Streamly.Prelude as Stream
268-- >>> import Streamly.Internal.Data.Stream.IsStream as Stream
269-- >>> import qualified Streamly.Data.Fold as Fold
270-- >>> import qualified Streamly.Internal.Data.Fold as Fold
272------------------------------------------------------------------------------
273-- Piping
274------------------------------------------------------------------------------
276-- | Use a 'Pipe' to transform a stream.
277--
278-- /Pre-release/
279--
280{-# INLINE transform #-}
281transform :: (IsStream t, Monad m) => Pipe m a b -> t m a -> t m b
282transform pipe xs = fromStreamD $ D.transform pipe (toStreamD xs)
284------------------------------------------------------------------------------
285-- Transformation Folds
286------------------------------------------------------------------------------
288-- | Right fold to a streaming monad.
289--
290-- > foldrS S.cons S.nil === id
291--
292-- 'foldrS' can be used to perform stateless stream to stream transformations
293-- like map and filter in general. It can be coupled with a scan to perform
294-- stateful transformations. However, note that the custom map and filter
295-- routines can be much more efficient than this due to better stream fusion.
296--
297-- >>> Stream.toList $ Stream.foldrS Stream.cons Stream.nil $ Stream.fromList [1..5]
298-- [1,2,3,4,5]
299--
300-- Find if any element in the stream is 'True':
301--
302-- >>> 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)
303-- [True]
304--
305-- Map (+2) on odd elements and filter out the even elements:
306--
307-- >>> 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)
308-- [3,5,7]
309--
310-- 'foldrM' can also be represented in terms of 'foldrS', however, the former
311-- is much more efficient:
312--
313-- > foldrM f z s = runIdentityT $ foldrS (\x xs -> lift $ f x (runIdentityT xs)) (lift z) s
314--
315-- /Pre-release/
316{-# INLINE foldrS #-}
317foldrS :: IsStream t => (a -> t m b -> t m b) -> t m b -> t m a -> t m b
318foldrS = K.foldrS
320-- | Right fold to a transformer monad. This is the most general right fold
321-- function. 'foldrS' is a special case of 'foldrT', however 'foldrS'
322-- implementation can be more efficient:
323--
324-- > foldrS = foldrT
325-- > foldrM f z s = runIdentityT $ foldrT (\x xs -> lift $ f x (runIdentityT xs)) (lift z) s
326--
327-- 'foldrT' can be used to translate streamly streams to other transformer
328-- monads e.g. to a different streaming type.
329--
330-- /Pre-release/
331{-# INLINE foldrT #-}
332foldrT :: (IsStream t, Monad m, Monad (s m), MonadTrans s)
333 => (a -> s m b -> s m b) -> s m b -> t m a -> s m b
334foldrT f z s = S.foldrT f z (toStreamS s)
336------------------------------------------------------------------------------
337-- Transformation by Mapping
338------------------------------------------------------------------------------
340-- |
341-- @
342-- mapM f = sequence . map f
343-- @
344--
345-- Apply a monadic function to each element of the stream and replace it with
346-- the output of the resulting action.
347--
348-- @
349-- > drain $ S.mapM putStr $ S.fromList ["a", "b", "c"]
350-- abc
351--
352-- drain $ S.replicateM 10 (return 1)
353-- & (fromSerial . S.mapM (\\x -> threadDelay 1000000 >> print x))
354--
355-- drain $ S.replicateM 10 (return 1)
356-- & (fromAsync . S.mapM (\\x -> threadDelay 1000000 >> print x))
357-- @
358--
359-- /Concurrent (do not use with 'fromParallel' on infinite streams)/
360--
361-- @since 0.1.0
362{-# INLINE_EARLY mapM #-}
363mapM :: (IsStream t, MonadAsync m) => (a -> m b) -> t m a -> t m b
364mapM = K.mapM
366{-# RULES "mapM serial" mapM = mapMSerial #-}
367{-# INLINE mapMSerial #-}
368mapMSerial :: Monad m => (a -> m b) -> SerialT m a -> SerialT m b
369mapMSerial = Serial.mapM
371-- |
372-- @
373-- sequence = mapM id
374-- @
375--
376-- Replace the elements of a stream of monadic actions with the outputs of
377-- those actions.
378--
379-- @
380-- > drain $ S.sequence $ S.fromList [putStr "a", putStr "b", putStrLn "c"]
381-- abc
382--
383-- drain $ S.replicateM 10 (return $ threadDelay 1000000 >> print 1)
384-- & (fromSerial . S.sequence)
385--
386-- drain $ S.replicateM 10 (return $ threadDelay 1000000 >> print 1)
387-- & (fromAsync . S.sequence)
388-- @
389--
390-- /Concurrent (do not use with 'fromParallel' on infinite streams)/
391--
392-- @since 0.1.0
393{-# INLINE sequence #-}
394sequence :: (IsStream t, MonadAsync m) => t m (m a) -> t m a
395sequence m = fromStreamS $ S.sequence (toStreamS m)
397------------------------------------------------------------------------------
398-- Mapping side effects
399------------------------------------------------------------------------------
401-- | Tap the data flowing through a stream into a 'Fold'. For example, you may
402-- add a tap to log the contents flowing through the stream. The fold is used
403-- only for effects, its result is discarded.
404--
405-- @
406-- Fold m a b
407-- |
408-- -----stream m a ---------------stream m a-----
409--
410-- @
411--
412-- >>> Stream.drain $ Stream.tap (Fold.drainBy print) (Stream.enumerateFromTo 1 2)
413-- 1
414-- 2
415--
416-- Compare with 'trace'.
417--
418-- @since 0.7.0
419{-# INLINE tap #-}
420tap :: (IsStream t, Monad m) => FL.Fold m a b -> t m a -> t m a
421tap f xs = D.fromStreamD $ D.tap f (D.toStreamD xs)
423-- XXX Remove this. It can be expressed in terms of Fold.sampleFromThen.
424--
425-- | @tapOffsetEvery offset n@ taps every @n@th element in the stream
426-- starting at @offset@. @offset@ can be between @0@ and @n - 1@. Offset 0
427-- means start at the first element in the stream. If the offset is outside
428-- this range then @offset `mod` n@ is used as offset.
429--
430-- >>> Stream.drain $ Stream.tapOffsetEvery 0 2 (Fold.rmapM print Fold.toList) $ Stream.enumerateFromTo 0 10
431-- [0,2,4,6,8,10]
433--
434-- /Pre-release/
435--
436{-# INLINE tapOffsetEvery #-}
437tapOffsetEvery :: (IsStream t, Monad m)
438 => Int -> Int -> FL.Fold m a b -> t m a -> t m a
439tapOffsetEvery offset n f xs =
440 D.fromStreamD $ D.tapOffsetEvery offset n f (D.toStreamD xs)
442-- | Redirect a copy of the stream to a supplied fold and run it concurrently
443-- in an independent thread. The fold may buffer some elements. The buffer size
444-- is determined by the prevailing 'maxBuffer' setting.
445--
446-- @
447-- Stream m a -> m b
448-- |
449-- -----stream m a ---------------stream m a-----
450--
451-- @
452--
453-- @
454-- > S.drain $ S.tapAsync (S.mapM_ print) (S.enumerateFromTo 1 2)
455-- 1
456-- 2
457-- @
458--
459-- Exceptions from the concurrently running fold are propagated to the current
460-- computation. Note that, because of buffering in the fold, exceptions may be
461-- delayed and may not correspond to the current element being processed in the
462-- parent stream, but we guarantee that before the parent stream stops the tap
463-- finishes and all exceptions from it are drained.
464--
465--
466-- Compare with 'tap'.
467--
468-- /Pre-release/
469{-# INLINE tapAsync #-}
470tapAsync :: (IsStream t, MonadAsync m) => FL.Fold m a b -> t m a -> t m a
471tapAsync f xs = D.fromStreamD $ Par.tapAsyncF f (D.toStreamD xs)
473-- | @pollCounts predicate transform fold stream@ counts those elements in the
474-- stream that pass the @predicate@. The resulting count stream is sent to
475-- another thread which transforms it using @transform@ and then folds it using
476-- @fold@. The thread is automatically cleaned up if the stream stops or
477-- aborts due to exception.
478--
479-- For example, to print the count of elements processed every second:
480--
481-- @
482-- > S.drain $ S.pollCounts (const True) (S.rollingMap (-) . S.delayPost 1) (FL.drainBy print)
483-- $ S.enumerateFrom 0
484-- @
485--
486-- Note: This may not work correctly on 32-bit machines.
487--
488-- /Pre-release/
489--
490{-# INLINE pollCounts #-}
491pollCounts ::
492 (IsStream t, MonadAsync m)
493 => (a -> Bool)
494 -> (t m Int -> t m Int)
495 -> Fold m Int b
496 -> t m a
497 -> t m a
498pollCounts predicate transf f xs =
499 D.fromStreamD
500 $ D.pollCounts predicate (D.toStreamD . transf . D.fromStreamD) f
501 $ D.toStreamD xs
503-- | Calls the supplied function with the number of elements consumed
504-- every @n@ seconds. The given function is run in a separate thread
505-- until the end of the stream. In case there is an exception in the
506-- stream the thread is killed during the next major GC.
507--
508-- Note: The action is not guaranteed to run if the main thread exits.
509--
510-- @
511-- > delay n = threadDelay (round $ n * 1000000) >> return n
512-- > S.drain $ S.tapRate 2 (\\n -> print $ show n ++ " elements processed") (delay 1 S.|: delay 0.5 S.|: delay 0.5 S.|: S.nil)
513-- 2 elements processed
514-- 1 elements processed
515-- @
516--
517-- Note: This may not work correctly on 32-bit machines.
518--
519-- /Pre-release/
520{-# INLINE tapRate #-}
521tapRate ::
522 (IsStream t, MonadAsync m, MonadCatch m)
523 => Double
524 -> (Int -> m b)
525 -> t m a
526 -> t m a
527tapRate n f xs = D.fromStreamD $ D.tapRate n f $ D.toStreamD xs
529-- | Apply a monadic function to each element flowing through the stream and
530-- discard the results.
531--
532-- @
533-- > S.drain $ S.trace print (S.enumerateFromTo 1 2)
534-- 1
535-- 2
536-- @
537--
538-- Compare with 'tap'.
539--
540-- @since 0.7.0
541{-# INLINE trace #-}
542trace :: (IsStream t, MonadAsync m) => (a -> m b) -> t m a -> t m a
543trace f = mapM (\x -> void (f x) >> return x)
545-- | Perform a side effect before yielding each element of the stream and
546-- discard the results.
547--
548-- @
549-- > S.drain $ S.trace_ (print "got here") (S.enumerateFromTo 1 2)
550-- "got here"
551-- "got here"
552-- @
553--
554-- Same as 'interspersePrefix_' but always serial.
555--
556-- See also: 'trace'
557--
558-- /Pre-release/
559{-# INLINE trace_ #-}
560trace_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
561trace_ eff = Serial.mapM (\x -> eff >> return x)
563------------------------------------------------------------------------------
564-- Scanning with a Fold
565------------------------------------------------------------------------------
567-- | Scan a stream using the given monadic fold.
568--
569-- >>> Stream.toList $ Stream.takeWhile (< 10) $ Stream.scan Fold.sum (Stream.fromList [1..10])
570-- [0,1,3,6]
571--
572-- @since 0.7.0
573{-# INLINE scan #-}
574scan :: (IsStream t, Monad m) => Fold m a b -> t m a -> t m b
575scan = P.scanOnce
577-- | Postscan a stream using the given monadic fold.
578--
579-- The following example extracts the input stream up to a point where the
580-- running average of elements is no more than 10:
581--
582-- >>> import Data.Maybe (fromJust)
583-- >>> let avg = Fold.teeWith (/) Fold.sum (fmap fromIntegral Fold.length)
584-- >>> :{
585-- Stream.toList
586-- $ Stream.map (fromJust . fst)
587-- $ Stream.takeWhile (\(_,x) -> x <= 10)
588-- $ Stream.postscan (Fold.tee Fold.last avg) (Stream.enumerateFromTo 1.0 100.0)
589-- :}
590-- [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]
591--
592-- @since 0.7.0
593{-# INLINE postscan #-}
594postscan :: (IsStream t, Monad m) => Fold m a b -> t m a -> t m b
595postscan = P.postscanOnce
597------------------------------------------------------------------------------
598-- Scanning - Transformation by Folding
599------------------------------------------------------------------------------
601-- XXX It may be useful to have a version of scan where we can keep the
602-- accumulator independent of the value emitted. So that we do not necessarily
603-- have to keep a value in the accumulator which we are not using. We can pass
604-- an extraction function that will take the accumulator and the current value
605-- of the element and emit the next value in the stream. That will also make it
606-- possible to modify the accumulator after using it. In fact, the step function
607-- can return new accumulator and the value to be emitted. The signature would
608-- be more like mapAccumL. Or we can change the signature of scanx to
609-- accommodate this.
610--
611-- | Strict left scan with an extraction function. Like 'scanl'', but applies a
612-- user supplied extraction function (the third argument) at each step. This is
613-- designed to work with the @foldl@ library. The suffix @x@ is a mnemonic for
614-- extraction.
615--
616-- /Since 0.2.0/
617--
618-- /Since: 0.7.0 (Monad m constraint)/
619{-# DEPRECATED scanx "Please use scanl followed by map instead." #-}
620{-# INLINE scanx #-}
621scanx :: (IsStream t, Monad m) => (x -> a -> x) -> x -> (x -> b) -> t m a -> t m b
622scanx = P.scanlx'
624-- XXX this needs to be concurrent
625-- XXX because of the use of D.cons for appending, scanlM' has quadratic
626-- complexity when iterated over a stream. We should use StreamK style scanlM'
627-- for linear performance on iteration.
628--
629-- | Like 'scanl'' but with a monadic step function and a monadic seed.
630--
631-- /Since: 0.4.0/
632--
633-- /Since: 0.8.0 (signature change)/
634{-# INLINE scanlM' #-}
635scanlM' :: (IsStream t, Monad m) => (b -> a -> m b) -> m b -> t m a -> t m b
636scanlM' step begin m = fromStreamD $ D.scanlM' step begin $ toStreamD m
638-- XXX because of the use of D.cons for appending, scanl' has quadratic
639-- complexity when iterated over a stream. We should use StreamK style scanlM'
640-- for linear performance on iteration.
642-- | Strict left scan. Like 'map', 'scanl'' too is a one to one transformation,
643-- however it adds an extra element.
644--
645-- @
646-- > S.toList $ S.scanl' (+) 0 $ fromList [1,2,3,4]
647-- [0,1,3,6,10]
648-- @
649--
650-- @
651-- > S.toList $ S.scanl' (flip (:)) [] $ S.fromList [1,2,3,4]
652-- [[],[1],[2,1],[3,2,1],[4,3,2,1]]
653-- @
654--
655-- The output of 'scanl'' is the initial value of the accumulator followed by
656-- all the intermediate steps and the final result of 'foldl''.
657--
658-- By streaming the accumulated state after each fold step, we can share the
659-- state across multiple stages of stream composition. Each stage can modify or
660-- extend the state, do some processing with it and emit it for the next stage,
661-- thus modularizing the stream processing. This can be useful in
662-- stateful or event-driven programming.
663--
664-- Consider the following monolithic example, computing the sum and the product
665-- of the elements in a stream in one go using a @foldl'@:
666--
667-- @
668-- > S.foldl' (\\(s, p) x -> (s + x, p * x)) (0,1) $ S.fromList \[1,2,3,4]
669-- (10,24)
670-- @
671--
672-- Using @scanl'@ we can make it modular by computing the sum in the first
673-- stage and passing it down to the next stage for computing the product:
674--
675-- @
676-- > S.foldl' (\\(_, p) (s, x) -> (s, p * x)) (0,1)
677-- $ S.scanl' (\\(s, _) x -> (s + x, x)) (0,1)
678-- $ S.fromList \[1,2,3,4]
679-- (10,24)
680-- @
681--
682-- IMPORTANT: 'scanl'' evaluates the accumulator to WHNF. To avoid building
683-- lazy expressions inside the accumulator, it is recommended that a strict
684-- data structure is used for accumulator.
685--
686-- See also: 'usingStateT'
687--
688-- @since 0.2.0
689{-# INLINE scanl' #-}
690scanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
691scanl' step z m = fromStreamS $ S.scanl' step z $ toStreamS m
693-- | Like 'scanl'' but does not stream the initial value of the accumulator.
694--
695-- > postscanl' f z xs = S.drop 1 $ S.scanl' f z xs
696--
697-- @since 0.7.0
698{-# INLINE postscanl' #-}
699postscanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
700postscanl' step z m = fromStreamD $ D.postscanl' step z $ toStreamD m
702-- XXX prescanl does not sound very useful, enable only if there is a
703-- compelling use case.
704--
705-- | Like scanl' but does not stream the final value of the accumulator.
706--
707-- /Pre-release/
708{-# INLINE prescanl' #-}
709prescanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
710prescanl' step z m = fromStreamD $ D.prescanl' step z $ toStreamD m
712-- XXX this needs to be concurrent
713-- | Like prescanl' but with a monadic step function and a monadic seed.
714--
715-- /Pre-release/
716{-# INLINE prescanlM' #-}
717prescanlM' :: (IsStream t, Monad m) => (b -> a -> m b) -> m b -> t m a -> t m b
718prescanlM' step z m = fromStreamD $ D.prescanlM' step z $ toStreamD m
720-- XXX this needs to be concurrent
721-- | Like 'scanl1'' but with a monadic step function.
722--
723-- @since 0.6.0
724{-# INLINE scanl1M' #-}
725scanl1M' :: (IsStream t, Monad m) => (a -> a -> m a) -> t m a -> t m a
726scanl1M' step m = fromStreamD $ D.scanl1M' step $ toStreamD m
728-- | Like 'scanl'' but for a non-empty stream. The first element of the stream
729-- is used as the initial value of the accumulator. Does nothing if the stream
730-- is empty.
731--
732-- @
733-- > S.toList $ S.scanl1 (+) $ fromList [1,2,3,4]
734-- [1,3,6,10]
735-- @
736--
737-- @since 0.6.0
738{-# INLINE scanl1' #-}
739scanl1' :: (IsStream t, Monad m) => (a -> a -> a) -> t m a -> t m a
740scanl1' step m = fromStreamD $ D.scanl1' step $ toStreamD m
742------------------------------------------------------------------------------
743-- Filtering
744------------------------------------------------------------------------------
746-- | Modify a @t m a -> t m a@ stream transformation that accepts a predicate
747-- @(a -> b)@ to accept @((s, a) -> b)@ instead, provided a transformation @t m
748-- a -> t m (s, a)@. Convenient to filter with index or time.
749--
750-- @
751-- filterWithIndex = with indexed filter
752-- filterWithAbsTime = with timestamped filter
753-- filterWithRelTime = with timeIndexed filter
754-- @
755--
756-- /Pre-release/
757{-# INLINE with #-}
758with :: forall (t :: (Type -> Type) -> Type -> Type) m a b s. Functor (t m) =>
759 (t m a -> t m (s, a))
760 -> (((s, a) -> b) -> t m (s, a) -> t m (s, a))
761 -> (((s, a) -> b) -> t m a -> t m a)
762with f comb g = fmap snd . comb g . f
764-- | Include only those elements that pass a predicate.
765--
766-- @since 0.1.0
767{-# INLINE filter #-}
768#if __GLASGOW_HASKELL__ != 802
769-- GHC 8.2.2 crashes with this code, when used with "stack"
770filter :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m a
771filter p m = fromStreamS $ S.filter p $ toStreamS m
772#else
773filter :: IsStream t => (a -> Bool) -> t m a -> t m a
774filter = K.filter
775#endif
777-- | Same as 'filter' but with a monadic predicate.
778--
779-- @since 0.4.0
780{-# INLINE filterM #-}
781filterM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
782filterM p m = fromStreamD $ D.filterM p $ toStreamD m
784-- | Drop repeated elements that are adjacent to each other using the supplied
785-- comparison function.
786--
787-- @uniq = uniqBy (==)
788--
789-- To strip duplicate path separators:
790--
791-- @
792-- f x y = x == '/' && x == y
793-- Stream.toList $ Stream.uniqBy f $ Stream.fromList "//a//b"
794-- "/a/b"
795-- @
796--
797-- Space: @O(1)@
798--
799-- See also: 'nubBy'.
800--
801-- /Pre-release/
802--
803{-# INLINE uniqBy #-}
804uniqBy :: (IsStream t, Monad m, Functor (t m)) =>
805 (a -> a -> Bool) -> t m a -> t m a
806uniqBy eq =
807 catMaybes . rollingMap (\x y -> if x `eq` y then Nothing else Just y)
809-- | Drop repeated elements that are adjacent to each other.
810--
811-- @since 0.6.0
812{-# INLINE uniq #-}
813uniq :: (Eq a, IsStream t, Monad m) => t m a -> t m a
814uniq = fromStreamD . D.uniq . toStreamD
816-- | Strip all leading and trailing occurrences of an element passing a
817-- predicate and make all other consecutive occurrences uniq.
818--
819-- @
820-- prune p = dropWhileAround p $ uniqBy (x y -> p x && p y)
821-- @
822--
823-- @
824-- > Stream.pruneBy isSpace (Stream.fromList " hello world! ")
825-- "hello world!"
826-- @
827--
828-- Space: @O(1)@
829--
830-- /Unimplemented/
831{-# INLINE prune #-}
832prune ::
833 -- (IsStream t, Monad m, Eq a) =>
834 (a -> Bool) -> t m a -> t m a
835prune = error "Not implemented yet!"
837-- Possible implementation:
838-- @repeated =
839-- Stream.catMaybes . Stream.parseMany (Parser.groupBy (==) Fold.repeated)@
840--
841-- 'Fold.repeated' should return 'Just' when repeated, and 'Nothing' for a
842-- single element.
843--
844-- | Emit only repeated elements, once.
845--
846-- /Unimplemented/
847repeated :: -- (IsStream t, Monad m, Eq a) =>
848 t m a -> t m a
849repeated = undefined
851-- We can have more efficient implementations for nubOrd and nubInt by using
852-- Set and IntSet to find/remove duplication. For Hashable we can use a
853-- hashmap. Use rewrite rules to specialize to more efficient impls.
854--
855-- | Drop repeated elements anywhere in the stream.
856--
857-- /Caution: not scalable for infinite streams/
858--
859-- /See also: nubWindowBy/
860--
861-- /Unimplemented/
862--
863{-# INLINE nubBy #-}
864nubBy :: -- (IsStream t, Monad m) =>
865 (a -> a -> Bool) -> t m a -> t m a
866nubBy = undefined -- fromStreamD . D.nubBy . toStreamD
868-- | Drop repeated elements within the specified tumbling window in the stream.
869--
870-- @nubBy = nubWindowBy maxBound@
871--
872-- /Unimplemented/
873--
874{-# INLINE nubWindowBy #-}
875nubWindowBy :: -- (IsStream t, Monad m) =>
876 Int -> (a -> a -> Bool) -> t m a -> t m a
877nubWindowBy = undefined -- fromStreamD . D.nubWithinBy . toStreamD
879-- | Deletes the first occurrence of the element in the stream that satisfies
880-- the given equality predicate.
881--
882-- @
883-- > S.toList $ S.deleteBy (==) 3 $ S.fromList [1,3,3,5]
884-- [1,3,5]
885-- @
886--
887-- @since 0.6.0
888{-# INLINE deleteBy #-}
889deleteBy :: (IsStream t, Monad m) => (a -> a -> Bool) -> a -> t m a -> t m a
890deleteBy cmp x m = fromStreamS $ S.deleteBy cmp x (toStreamS m)
892------------------------------------------------------------------------------
893-- Lossy Buffering
894------------------------------------------------------------------------------
896-- XXX We could use 'maxBuffer Block/Drop/Rotate/Sample' instead. However we
897-- may want to have the evaluation rate independent of the sampling rate. To
898-- support that we can decouple evaluation and sampling in independent stages.
899-- The sampling stage would strictly evaluate and sample, the evaluation stage
900-- would control the evaluation rate.
902-- | Evaluate the input stream continuously and keep only the oldest @n@
903-- elements in the buffer, discard the new ones when the buffer is full. When
904-- the output stream is evaluated it consumes the values from the buffer in a
905-- FIFO manner.
906--
907-- /Unimplemented/
908--
909{-# INLINE sampleOld #-}
910sampleOld :: -- (IsStream t, Monad m) =>
911 Int -> t m a -> t m a
912sampleOld = undefined
914-- | Evaluate the input stream continuously and keep only the latest @n@
915-- elements in a ring buffer, keep discarding the older ones to make space for
916-- the new ones. When the output stream is evaluated it consumes the values
917-- from the buffer in a FIFO manner.
918--
919-- /Unimplemented/
920--
921{-# INLINE sampleNew #-}
922sampleNew :: -- (IsStream t, Monad m) =>
923 Int -> t m a -> t m a
924sampleNew = undefined
926-- | Like 'sampleNew' but samples at uniform intervals to match the consumer
927-- rate. Note that 'sampleNew' leads to non-uniform sampling depending on the
928-- consumer pattern.
929--
930-- /Unimplemented/
931--
932{-# INLINE sampleRate #-}
933sampleRate :: -- (IsStream t, Monad m) =>
934 Double -> t m a -> t m a
935sampleRate = undefined
937------------------------------------------------------------------------------
938-- Trimming
939------------------------------------------------------------------------------
941-- | Same as 'takeWhile' but with a monadic predicate.
942--
943-- @since 0.4.0
944{-# INLINE takeWhileM #-}
945takeWhileM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
946takeWhileM p m = fromStreamD $ D.takeWhileM p $ toStreamD m
948-- See the lastN fold for impl hints. Use a Data.Array based ring buffer.
949--
950-- takeLast n = Stream.concatM . fmap Array.toStream . fold Fold.lastN
951--
952-- | Take @n@ elements at the end of the stream.
953--
954-- O(n) space, where n is the number elements taken.
955--
956-- /Unimplemented/
957{-# INLINE takeLast #-}
958takeLast :: -- (IsStream t, Monad m) =>
959 Int -> t m a -> t m a
960takeLast = undefined -- fromStreamD $ D.takeLast n $ toStreamD m
962-- | Take time interval @i@ seconds at the end of the stream.
963--
964-- O(n) space, where n is the number elements taken.
965--
966-- /Unimplemented/
967{-# INLINE takeLastInterval #-}
968takeLastInterval :: -- (IsStream t, Monad m) =>
969 Double -> t m a -> t m a
970takeLastInterval = undefined -- fromStreamD $ D.takeLast n $ toStreamD m
972-- | Take all consecutive elements at the end of the stream for which the
973-- predicate is true.
974--
975-- O(n) space, where n is the number elements taken.
976--
977-- /Unimplemented/
978{-# INLINE takeWhileLast #-}
979takeWhileLast :: -- (IsStream t, Monad m) =>
980 (a -> Bool) -> t m a -> t m a
981takeWhileLast = undefined -- fromStreamD $ D.takeWhileLast n $ toStreamD m
983-- | Like 'takeWhile' and 'takeWhileLast' combined.
984--
985-- O(n) space, where n is the number elements taken from the end.
986--
987-- /Unimplemented/
988{-# INLINE takeWhileAround #-}
989takeWhileAround :: -- (IsStream t, Monad m) =>
990 (a -> Bool) -> t m a -> t m a
991takeWhileAround = undefined -- fromStreamD $ D.takeWhileAround n $ toStreamD m
993-- | @takeInterval duration@ yields stream elements upto specified time
994-- @duration@. The duration starts when the stream is evaluated for the first
995-- time, before the first element is yielded. The time duration is checked
996-- before generating each element, if the duration has expired the stream
997-- stops.
998--
999-- The total time taken in executing the stream is guaranteed to be /at least/
1000-- @duration@, however, because the duration is checked before generating an
1001-- element, the upper bound is indeterminate and depends on the time taken in
1002-- generating and processing the last element.
1004-- No element is yielded if the duration is zero. At least one element is
1005-- yielded if the duration is non-zero.
1007-- /Pre-release/
1009{-# INLINE takeInterval #-}
1010takeInterval ::(MonadIO m, IsStream t, TimeUnit64 d) => d -> t m a -> t m a
1011takeInterval d = fromStreamD . D.takeByTime d . toStreamD
1013-- | Drop elements in the stream as long as the predicate succeeds and then
1014-- take the rest of the stream.
1016-- @since 0.1.0
1017{-# INLINE dropWhile #-}
1018dropWhile :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m a
1019dropWhile p m = fromStreamS $ S.dropWhile p $ toStreamS m
1021-- | Same as 'dropWhile' but with a monadic predicate.
1023-- @since 0.4.0
1024{-# INLINE dropWhileM #-}
1025dropWhileM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
1026dropWhileM p m = fromStreamD $ D.dropWhileM p $ toStreamD m
1028-- | @dropInterval duration@ drops stream elements until specified @duration@ has
1029-- passed. The duration begins when the stream is evaluated for the first
1030-- time. The time duration is checked /after/ generating a stream element, the
1031-- element is yielded if the duration has expired otherwise it is dropped.
1033-- The time elapsed before starting to generate the first element is /at most/
1034-- @duration@, however, because the duration expiry is checked after the
1035-- element is generated, the lower bound is indeterminate and depends on the
1036-- time taken in generating an element.
1038-- All elements are yielded if the duration is zero.
1040-- /Pre-release/
1042{-# INLINE dropInterval #-}
1043dropInterval ::(MonadIO m, IsStream t, TimeUnit64 d) => d -> t m a -> t m a
1044dropInterval d = fromStreamD . D.dropByTime d . toStreamD
1046-- | Drop @n@ elements at the end of the stream.
1048-- O(n) space, where n is the number elements dropped.
1050-- /Unimplemented/
1051{-# INLINE dropLast #-}
1052dropLast :: -- (IsStream t, Monad m) =>
1053 Int -> t m a -> t m a
1054dropLast = undefined -- fromStreamD $ D.dropLast n $ toStreamD m
1056-- | Drop time interval @i@ seconds at the end of the stream.
1058-- O(n) space, where n is the number elements dropped.
1060-- /Unimplemented/
1061{-# INLINE dropLastInterval #-}
1062dropLastInterval :: -- (IsStream t, Monad m) =>
1063 Int -> t m a -> t m a
1064dropLastInterval = undefined
1066-- | Drop all consecutive elements at the end of the stream for which the
1067-- predicate is true.
1069-- O(n) space, where n is the number elements dropped.
1071-- /Unimplemented/
1072{-# INLINE dropWhileLast #-}
1073dropWhileLast :: -- (IsStream t, Monad m) =>
1074 (a -> Bool) -> t m a -> t m a
1075dropWhileLast = undefined -- fromStreamD $ D.dropWhileLast n $ toStreamD m
1077-- | Like 'dropWhile' and 'dropWhileLast' combined.
1079-- O(n) space, where n is the number elements dropped from the end.
1081-- /Unimplemented/
1082{-# INLINE dropWhileAround #-}
1083dropWhileAround :: -- (IsStream t, Monad m) =>
1084 (a -> Bool) -> t m a -> t m a
1085dropWhileAround = undefined -- fromStreamD $ D.dropWhileAround n $ toStreamD m
1087------------------------------------------------------------------------------
1088-- Inserting Elements
1089------------------------------------------------------------------------------
1091-- | @insertBy cmp elem stream@ inserts @elem@ before the first element in
1092-- @stream@ that is less than @elem@ when compared using @cmp@.
1094-- @
1095-- insertBy cmp x = 'mergeBy' cmp ('yield' x)
1096-- @
1098-- @
1099-- > S.toList $ S.insertBy compare 2 $ S.fromList [1,3,5]
1100-- [1,2,3,5]
1101-- @
1103-- @since 0.6.0
1104{-# INLINE insertBy #-}
1105insertBy ::
1106 (IsStream t, Monad m) => (a -> a -> Ordering) -> a -> t m a -> t m a
1107insertBy cmp x m = fromStreamS $ S.insertBy cmp x (toStreamS m)
1109-- | Insert a pure value between successive elements of a stream.
1111-- >>> Stream.toList $ Stream.intersperse ',' $ Stream.fromList "hello"
1112-- "h,e,l,l,o"
1114-- @since 0.7.0
1115{-# INLINE intersperse #-}
1116intersperse :: (IsStream t, MonadAsync m) => a -> t m a -> t m a
1117intersperse a = fromStreamS . S.intersperse a . toStreamS
1119-- | Insert a side effect before consuming an element of a stream except the
1120-- first one.
1122-- >>> Stream.drain $ Stream.trace putChar $ Stream.intersperseM_ (putChar '.') $ Stream.fromList "hello"
1123-- h.e.l.l.o
1125-- /Pre-release/
1126{-# INLINE intersperseM_ #-}
1127intersperseM_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
1128intersperseM_ m = fromStreamD . D.intersperseM_ m . toStreamD
1130-- | Intersperse a monadic action into the input stream after every @n@
1131-- elements.
1133-- @
1134-- > S.toList $ S.intersperseBySpan 2 (return ',') $ S.fromList "hello"
1135-- "he,ll,o"
1136-- @
1138-- /Unimplemented/
1139{-# INLINE intersperseBySpan #-}
1140intersperseBySpan :: -- IsStream t =>
1141 Int -> m a -> t m a -> t m a
1142intersperseBySpan _n _f _xs = undefined
1144-- | Insert an effect and its output after consuming an element of a stream.
1146-- >>> Stream.toList $ Stream.trace putChar $ intersperseSuffix (putChar '.' >> return ',') $ Stream.fromList "hello"
1147-- h.,e.,l.,l.,o.,"h,e,l,l,o,"
1149-- /Pre-release/
1150{-# INLINE intersperseSuffix #-}
1151intersperseSuffix :: (IsStream t, Monad m) => m a -> t m a -> t m a
1152intersperseSuffix m = fromStreamD . D.intersperseSuffix m . toStreamD
1154-- | Insert a side effect after consuming an element of a stream.
1156-- @
1157-- > S.mapM_ putChar $ S.intersperseSuffix_ (threadDelay 1000000) $ S.fromList "hello"
1158-- @
1160-- /Pre-release/
1162{-# INLINE intersperseSuffix_ #-}
1163intersperseSuffix_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
1164intersperseSuffix_ m = fromStreamD . D.intersperseSuffix_ m . toStreamD
1166-- XXX Use an offset argument, like tapOffsetEvery
1168-- | Like 'intersperseSuffix' but intersperses an effectful action into the
1169-- input stream after every @n@ elements and after the last element.
1171-- >>> Stream.toList $ Stream.intersperseSuffixBySpan 2 (return ',') $ Stream.fromList "hello"
1172-- "he,ll,o,"
1174-- /Pre-release/
1176{-# INLINE intersperseSuffixBySpan #-}
1177intersperseSuffixBySpan :: (IsStream t, Monad m)
1178 => Int -> m a -> t m a -> t m a
1179intersperseSuffixBySpan n eff =
1180 fromStreamD . D.intersperseSuffixBySpan n eff . toStreamD
1182-- | Insert a side effect before consuming an element of a stream.
1184-- >>> Stream.toList $ Stream.trace putChar $ Stream.interspersePrefix_ (putChar '.' >> return ',') $ Stream.fromList "hello"
1185-- .h.e.l.l.o"hello"
1187-- Same as 'trace_' but may be concurrent.
1189-- /Concurrent/
1191-- /Pre-release/
1193{-# INLINE interspersePrefix_ #-}
1194interspersePrefix_ :: (IsStream t, MonadAsync m) => m b -> t m a -> t m a
1195interspersePrefix_ m = mapM (\x -> void m >> return x)
1197------------------------------------------------------------------------------
1198-- Inserting Time
1199------------------------------------------------------------------------------
1201-- Note: delay must be serial.
1203-- | Introduce a delay of specified seconds before consuming an element of the
1204-- stream except the first one.
1206-- >>> Stream.mapM_ print $ Stream.timestamped $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
1207-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),1)
1208-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),2)
1209-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),3)
1211-- @since 0.8.0
1213{-# INLINE delay #-}
1214delay :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
1215delay n = intersperseM_ $ liftIO $ threadDelay $ round $ n * 1000000
1217-- Note: delay must be serial.
1219-- | Introduce a delay of specified seconds after consuming an element of a
1220-- stream.
1222-- >>> Stream.mapM_ print $ Stream.timestamped $ Stream.delayPost 1 $ Stream.enumerateFromTo 1 3
1223-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),1)
1224-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),2)
1225-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),3)
1227-- /Pre-release/
1229{-# INLINE delayPost #-}
1230delayPost :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
1231delayPost n = intersperseSuffix_ $ liftIO $ threadDelay $ round $ n * 1000000
1233-- Note: delay must be serial, that's why 'trace_' is used.
1235-- | Introduce a delay of specified seconds before consuming an element of a
1236-- stream.
1238-- >>> Stream.mapM_ print $ Stream.timestamped $ Stream.delayPre 1 $ Stream.enumerateFromTo 1 3
1239-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),1)
1240-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),2)
1241-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),3)
1243-- /Pre-release/
1245{-# INLINE delayPre #-}
1246delayPre :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
1247delayPre n = trace_ $ liftIO $ threadDelay $ round $ n * 1000000
1249------------------------------------------------------------------------------
1250-- Reorder in sequence
1251------------------------------------------------------------------------------
1253-- | Buffer until the next element in sequence arrives. The function argument
1254-- determines the difference in sequence numbers. This could be useful in
1255-- implementing sequenced streams, for example, TCP reassembly.
1257-- /Unimplemented/
1259{-# INLINE reassembleBy #-}
1260reassembleBy
1261 :: -- (IsStream t, Monad m) =>
1262 Fold m a b
1263 -> (a -> a -> Int)
1264 -> t m a
1265 -> t m b
1266reassembleBy = undefined
1268------------------------------------------------------------------------------
1269-- Position Indexing
1270------------------------------------------------------------------------------
1272-- |
1273-- > indexed = S.postscanl' (\(i, _) x -> (i + 1, x)) (-1,undefined)
1274-- > indexed = S.zipWith (,) (S.enumerateFrom 0)
1276-- Pair each element in a stream with its index, starting from index 0.
1278-- >>> Stream.toList $ Stream.indexed $ Stream.fromList "hello"
1279-- [(0,'h'),(1,'e'),(2,'l'),(3,'l'),(4,'o')]
1281-- @since 0.6.0
1282{-# INLINE indexed #-}
1283indexed :: (IsStream t, Monad m) => t m a -> t m (Int, a)
1284indexed = fromStreamD . D.indexed . toStreamD
1286-- |
1287-- > indexedR n = S.postscanl' (\(i, _) x -> (i - 1, x)) (n + 1,undefined)
1288-- > indexedR n = S.zipWith (,) (S.enumerateFromThen n (n - 1))
1290-- Pair each element in a stream with its index, starting from the
1291-- given index @n@ and counting down.
1293-- >>> Stream.toList $ Stream.indexedR 10 $ Stream.fromList "hello"
1294-- [(10,'h'),(9,'e'),(8,'l'),(7,'l'),(6,'o')]
1296-- @since 0.6.0
1297{-# INLINE indexedR #-}
1298indexedR :: (IsStream t, Monad m) => Int -> t m a -> t m (Int, a)
1299indexedR n = fromStreamD . D.indexedR n . toStreamD
1301-------------------------------------------------------------------------------
1302-- Time Indexing
1303-------------------------------------------------------------------------------
1305-- Note: The timestamp stream must be the second stream in the zip so that the
1306-- timestamp is generated after generating the stream element and not before.
1307-- If we do not do that then the following example will generate the same
1308-- timestamp for first two elements:
1310-- S.mapM_ print $ S.timestamped $ S.delay $ S.enumerateFromTo 1 3
1312-- | Pair each element in a stream with an absolute timestamp, using a clock of
1313-- specified granularity. The timestamp is generated just before the element
1314-- is consumed.
1316-- >>> Stream.mapM_ print $ Stream.timestampWith 0.01 $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
1317-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),1)
1318-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),2)
1319-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),3)
1321-- /Pre-release/
1323{-# INLINE timestampWith #-}
1324timestampWith :: (IsStream t, MonadAsync m, Functor (t m))
1325 => Double -> t m a -> t m (AbsTime, a)
1326timestampWith g stream = Z.zipWith (flip (,)) stream (absTimesWith g)
1328-- TBD: check performance vs a custom implementation without using zipWith.
1330-- /Pre-release/
1332{-# INLINE timestamped #-}
1333timestamped :: (IsStream t, MonadAsync m, Functor (t m))
1334 => t m a -> t m (AbsTime, a)
1335timestamped = timestampWith 0.01
1337-- | Pair each element in a stream with relative times starting from 0, using a
1338-- clock with the specified granularity. The time is measured just before the
1339-- element is consumed.
1341-- >>> Stream.mapM_ print $ Stream.timeIndexWith 0.01 $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
1342-- (RelTime64 (NanoSecond64 ...),1)
1343-- (RelTime64 (NanoSecond64 ...),2)
1344-- (RelTime64 (NanoSecond64 ...),3)
1346-- /Pre-release/
1348{-# INLINE timeIndexWith #-}
1349timeIndexWith :: (IsStream t, MonadAsync m, Functor (t m))
1350 => Double -> t m a -> t m (RelTime64, a)
1351timeIndexWith g stream = Z.zipWith (flip (,)) stream (relTimesWith g)
1353-- | Pair each element in a stream with relative times starting from 0, using a
1354-- 10 ms granularity clock. The time is measured just before the element is
1355-- consumed.
1357-- >>> Stream.mapM_ print $ Stream.timeIndexed $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
1358-- (RelTime64 (NanoSecond64 ...),1)
1359-- (RelTime64 (NanoSecond64 ...),2)
1360-- (RelTime64 (NanoSecond64 ...),3)
1362-- /Pre-release/
1364{-# INLINE timeIndexed #-}
1365timeIndexed :: (IsStream t, MonadAsync m, Functor (t m))
1366 => t m a -> t m (RelTime64, a)
1367timeIndexed = timeIndexWith 0.01
1369------------------------------------------------------------------------------
1370-- Searching
1371------------------------------------------------------------------------------
1373-- | Find all the indices where the value of the element in the stream is equal
1374-- to the given value.
1376-- > elemIndices a = findIndices (== a)
1378-- @since 0.5.0
1379{-# INLINE elemIndices #-}
1380elemIndices :: (IsStream t, Eq a, Monad m) => a -> t m a -> t m Int
1381elemIndices a = findIndices (== a)
1383------------------------------------------------------------------------------
1384-- Rolling map
1385------------------------------------------------------------------------------
1387-- XXX this is not a one-to-one map so calling it map may not be right.
1388-- We can perhaps call it zipWithTail or rollWith.
1390-- | Apply a function on every two successive elements of a stream. If the
1391-- stream consists of a single element the output is an empty stream.
1393-- This is the stream equivalent of the list idiom @zipWith f xs (tail xs)@.
1395-- /Pre-release/
1397{-# INLINE rollingMap #-}
1398rollingMap :: (IsStream t, Monad m) => (a -> a -> b) -> t m a -> t m b
1399rollingMap f m = fromStreamD $ D.rollingMap f $ toStreamD m
1401-- | Like 'rollingMap' but with an effectful map function.
1403-- /Pre-release/
1405{-# INLINE rollingMapM #-}
1406rollingMapM :: (IsStream t, Monad m) => (a -> a -> m b) -> t m a -> t m b
1407rollingMapM f m = fromStreamD $ D.rollingMapM f $ toStreamD m
1409------------------------------------------------------------------------------
1410-- Maybe Streams
1411------------------------------------------------------------------------------
1413-- | Map a 'Maybe' returning function to a stream, filter out the 'Nothing'
1414-- elements, and return a stream of values extracted from 'Just'.
1416-- Equivalent to:
1418-- @
1419-- mapMaybe f = S.map 'fromJust' . S.filter 'isJust' . S.map f
1420-- @
1422-- @since 0.3.0
1423{-# INLINE mapMaybe #-}
1424mapMaybe :: (IsStream t, Monad m) => (a -> Maybe b) -> t m a -> t m b
1425mapMaybe f m = fromStreamS $ S.mapMaybe f $ toStreamS m
1427-- | Like 'mapMaybe' but maps a monadic function.
1429-- Equivalent to:
1431-- @
1432-- mapMaybeM f = S.map 'fromJust' . S.filter 'isJust' . S.mapM f
1433-- @
1435-- /Concurrent (do not use with 'fromParallel' on infinite streams)/
1437-- @since 0.3.0
1438{-# INLINE_EARLY mapMaybeM #-}
1439mapMaybeM :: (IsStream t, MonadAsync m, Functor (t m))
1440 => (a -> m (Maybe b)) -> t m a -> t m b
1441mapMaybeM f = fmap fromJust . filter isJust . K.mapM f
1443{-# RULES "mapMaybeM serial" mapMaybeM = mapMaybeMSerial #-}
1444{-# INLINE mapMaybeMSerial #-}
1445mapMaybeMSerial :: Monad m => (a -> m (Maybe b)) -> SerialT m a -> SerialT m b
1446mapMaybeMSerial f m = fromStreamD $ D.mapMaybeM f $ toStreamD m
1448-- | In a stream of 'Maybe's, discard 'Nothing's and unwrap 'Just's.
1450-- /Pre-release/
1452catMaybes :: (IsStream t, Monad m, Functor (t m)) => t m (Maybe a) -> t m a
1453catMaybes = fmap fromJust . filter isJust
1455------------------------------------------------------------------------------
1456-- Either streams
1457------------------------------------------------------------------------------
1459-- | Discard 'Right's and unwrap 'Left's in an 'Either' stream.
1461-- /Pre-release/
1463lefts :: (IsStream t, Monad m, Functor (t m)) => t m (Either a b) -> t m a
1464lefts = fmap (fromLeft undefined) . filter isLeft
1466-- | Discard 'Left's and unwrap 'Right's in an 'Either' stream.
1468-- /Pre-release/
1470rights :: (IsStream t, Monad m, Functor (t m)) => t m (Either a b) -> t m b
1471rights = fmap (fromRight undefined) . filter isRight
1473------------------------------------------------------------------------------
1474-- Concurrent Application
1475------------------------------------------------------------------------------
1477-- | Parallel transform application operator; applies a stream transformation
1478-- function @t m a -> t m b@ to a stream @t m a@ concurrently; the input stream
1479-- is evaluated asynchronously in an independent thread yielding elements to a
1480-- buffer and the transformation function runs in another thread consuming the
1481-- input from the buffer. '|$' is just like regular function application
1482-- operator '$' except that it is concurrent.
1484-- If you read the signature as @(t m a -> t m b) -> (t m a -> t m b)@ you can
1485-- look at it as a transformation that converts a transform function to a
1486-- buffered concurrent transform function.
1488-- The following code prints a value every second even though each stage adds a
1489-- 1 second delay.
1492-- >>> import Control.Concurrent (threadDelay)
1493-- >>> import Streamly.Prelude ((|$))
1494-- >>> :{
1495-- Stream.drain $
1496-- Stream.mapM (\x -> threadDelay 1000000 >> print x)
1497-- |$ Stream.replicateM 3 (threadDelay 1000000 >> return 1)
1498-- :}
1499-- 1
1500-- 1
1501-- 1
1503-- /Concurrent/
1505-- /Since: 0.3.0 ("Streamly")/
1507-- @since 0.8.0
1508{-# INLINE (|$) #-}
1509(|$) :: (IsStream t, MonadAsync m) => (t m a -> t m b) -> (t m a -> t m b)
1510-- (|$) f = f . Async.mkAsync
1511(|$) f = f . Par.mkParallel
1513infixr 0 |$
1515-- | Same as '|$'.
1517-- /Internal/
1519{-# INLINE applyAsync #-}
1520applyAsync :: (IsStream t, MonadAsync m)
1521 => (t m a -> t m b) -> (t m a -> t m b)
1522applyAsync = (|$)
1524-- | Same as '|$' but with arguments reversed.
1526-- (|&) = flip (|$)
1528-- /Concurrent/
1530-- /Since: 0.3.0 ("Streamly")/
1532-- @since 0.8.0
1533{-# INLINE (|&) #-}
1534(|&) :: (IsStream t, MonadAsync m) => t m a -> (t m a -> t m b) -> t m b
1535x |& f = f |$ x
1537infixl 1 |&