on 03218ad help sign in
1571 lines 50 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 Control.Concurrent (threadDelay)
267-- >>> import Data.Function ((&))
268-- >>> import Streamly.Prelude ((|$))
269-- >>> import Prelude hiding ( filter, drop, dropWhile, take, takeWhile, foldr, map, mapM, sequence, reverse, foldr1 , scanl, scanl1)
270-- >>> import qualified Streamly.Prelude as Stream
271-- >>> import Streamly.Internal.Data.Stream.IsStream as Stream
272-- >>> import qualified Streamly.Data.Fold as Fold
273-- >>> import qualified Streamly.Internal.Data.Fold as Fold
275------------------------------------------------------------------------------
276-- Piping
277------------------------------------------------------------------------------
279-- | Use a 'Pipe' to transform a stream.
280--
281-- /Pre-release/
282--
283{-# INLINE transform #-}
284transform :: (IsStream t, Monad m) => Pipe m a b -> t m a -> t m b
285transform pipe xs = fromStreamD $ D.transform pipe (toStreamD xs)
287------------------------------------------------------------------------------
288-- Transformation Folds
289------------------------------------------------------------------------------
291-- | Right fold to a streaming monad.
292--
293-- > foldrS Stream.cons Stream.nil === id
294--
295-- 'foldrS' can be used to perform stateless stream to stream transformations
296-- like map and filter in general. It can be coupled with a scan to perform
297-- stateful transformations. However, note that the custom map and filter
298-- routines can be much more efficient than this due to better stream fusion.
299--
300-- >>> Stream.toList $ Stream.foldrS Stream.cons Stream.nil $ Stream.fromList [1..5]
301-- [1,2,3,4,5]
302--
303-- Find if any element in the stream is 'True':
304--
305-- >>> 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)
306-- [True]
307--
308-- Map (+2) on odd elements and filter out the even elements:
309--
310-- >>> 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)
311-- [3,5,7]
312--
313-- 'foldrM' can also be represented in terms of 'foldrS', however, the former
314-- is much more efficient:
315--
316-- > foldrM f z s = runIdentityT $ foldrS (\x xs -> lift $ f x (runIdentityT xs)) (lift z) s
317--
318-- /Pre-release/
319{-# INLINE foldrS #-}
320foldrS :: IsStream t => (a -> t m b -> t m b) -> t m b -> t m a -> t m b
321foldrS = K.foldrS
323-- | Right fold to a transformer monad. This is the most general right fold
324-- function. 'foldrS' is a special case of 'foldrT', however 'foldrS'
325-- implementation can be more efficient:
326--
327-- > foldrS = foldrT
328-- > foldrM f z s = runIdentityT $ foldrT (\x xs -> lift $ f x (runIdentityT xs)) (lift z) s
329--
330-- 'foldrT' can be used to translate streamly streams to other transformer
331-- monads e.g. to a different streaming type.
332--
333-- /Pre-release/
334{-# INLINE foldrT #-}
335foldrT :: (IsStream t, Monad m, Monad (s m), MonadTrans s)
336 => (a -> s m b -> s m b) -> s m b -> t m a -> s m b
337foldrT f z s = S.foldrT f z (toStreamS s)
339------------------------------------------------------------------------------
340-- Transformation by Mapping
341------------------------------------------------------------------------------
343-- |
344-- @
345-- mapM f = sequence . map f
346-- @
347--
348-- Apply a monadic function to each element of the stream and replace it with
349-- the output of the resulting action.
350--
351-- @
352-- >>> drain $ Stream.mapM putStr $ Stream.fromList ["a", "b", "c"]
353-- abc
354--
355-- >>> :{
356-- drain $ Stream.replicateM 10 (return 1)
357-- & (fromSerial . Stream.mapM (\x -> threadDelay 1000000 >> print x))
358-- :}
359-- 1
360-- ...
361-- 1
362--
363-- > drain $ Stream.replicateM 10 (return 1)
364-- & (fromAsync . Stream.mapM (\x -> threadDelay 1000000 >> print x))
365-- @
366--
367-- /Concurrent (do not use with 'fromParallel' on infinite streams)/
368--
369-- @since 0.1.0
370{-# INLINE_EARLY mapM #-}
371mapM :: (IsStream t, MonadAsync m) => (a -> m b) -> t m a -> t m b
372mapM = K.mapM
374{-# RULES "mapM serial" mapM = mapMSerial #-}
375{-# INLINE mapMSerial #-}
376mapMSerial :: Monad m => (a -> m b) -> SerialT m a -> SerialT m b
377mapMSerial = Serial.mapM
379-- |
380-- @
381-- sequence = mapM id
382-- @
383--
384-- Replace the elements of a stream of monadic actions with the outputs of
385-- those actions.
386--
387-- @
388-- >>> drain $ Stream.sequence $ Stream.fromList [putStr "a", putStr "b", putStrLn "c"]
389-- abc
390--
391-- >>> :{
392-- drain $ Stream.replicateM 10 (return $ threadDelay 1000000 >> print 1)
393-- & (fromSerial . Stream.sequence)
394-- :}
395-- 1
396-- ...
397-- 1
398--
399-- >>> :{
400-- drain $ Stream.replicateM 10 (return $ threadDelay 1000000 >> print 1)
401-- & (fromAsync . Stream.sequence)
402-- :}
403-- 1
404-- ...
405-- 1
406--
407-- @
408--
409-- /Concurrent (do not use with 'fromParallel' on infinite streams)/
410--
411-- @since 0.1.0
412{-# INLINE sequence #-}
413sequence :: (IsStream t, MonadAsync m) => t m (m a) -> t m a
414sequence m = fromStreamS $ S.sequence (toStreamS m)
416------------------------------------------------------------------------------
417-- Mapping side effects
418------------------------------------------------------------------------------
420-- | Tap the data flowing through a stream into a 'Fold'. For example, you may
421-- add a tap to log the contents flowing through the stream. The fold is used
422-- only for effects, its result is discarded.
423--
424-- @
425-- Fold m a b
426-- |
427-- -----stream m a ---------------stream m a-----
428--
429-- @
430--
431-- >>> Stream.drain $ Stream.tap (Fold.drainBy print) (Stream.enumerateFromTo 1 2)
432-- 1
433-- 2
434--
435-- Compare with 'trace'.
436--
437-- @since 0.7.0
438{-# INLINE tap #-}
439tap :: (IsStream t, Monad m) => FL.Fold m a b -> t m a -> t m a
440tap f xs = D.fromStreamD $ D.tap f (D.toStreamD xs)
442-- XXX Remove this. It can be expressed in terms of Fold.sampleFromThen.
443--
444-- | @tapOffsetEvery offset n@ taps every @n@th element in the stream
445-- starting at @offset@. @offset@ can be between @0@ and @n - 1@. Offset 0
446-- means start at the first element in the stream. If the offset is outside
447-- this range then @offset `mod` n@ is used as offset.
448--
449-- >>> Stream.drain $ Stream.tapOffsetEvery 0 2 (Fold.rmapM print Fold.toList) $ Stream.enumerateFromTo 0 10
450-- [0,2,4,6,8,10]
452--
453-- /Pre-release/
454--
455{-# INLINE tapOffsetEvery #-}
456tapOffsetEvery :: (IsStream t, Monad m)
457 => Int -> Int -> FL.Fold m a b -> t m a -> t m a
458tapOffsetEvery offset n f xs =
459 D.fromStreamD $ D.tapOffsetEvery offset n f (D.toStreamD xs)
461-- | Redirect a copy of the stream to a supplied fold and run it concurrently
462-- in an independent thread. The fold may buffer some elements. The buffer size
463-- is determined by the prevailing 'maxBuffer' setting.
464--
465-- @
466-- Stream m a -> m b
467-- |
468-- -----stream m a ---------------stream m a-----
469--
470-- @
471--
472-- @
473-- >>> Stream.drain $ Stream.tapAsync (Fold.drainBy print) (Stream.enumerateFromTo 1 2)
474-- 1
475-- 2
476--
477-- @
478--
479-- Exceptions from the concurrently running fold are propagated to the current
480-- computation. Note that, because of buffering in the fold, exceptions may be
481-- delayed and may not correspond to the current element being processed in the
482-- parent stream, but we guarantee that before the parent stream stops the tap
483-- finishes and all exceptions from it are drained.
484--
485--
486-- Compare with 'tap'.
487--
488-- /Pre-release/
489{-# INLINE tapAsync #-}
490tapAsync :: (IsStream t, MonadAsync m) => FL.Fold m a b -> t m a -> t m a
491tapAsync f xs = D.fromStreamD $ Par.tapAsyncF f (D.toStreamD xs)
493-- | @pollCounts predicate transform fold stream@ counts those elements in the
494-- stream that pass the @predicate@. The resulting count stream is sent to
495-- another thread which transforms it using @transform@ and then folds it using
496-- @fold@. The thread is automatically cleaned up if the stream stops or
497-- aborts due to exception.
498--
499-- For example, to print the count of elements processed every second:
500--
501-- @
502-- > Stream.drain $ Stream.pollCounts (const True) (Stream.rollingMap (-) . Stream.delayPost 1) (FLold.drainBy print)
503-- $ Stream.enumerateFrom 0
504-- @
505--
506-- Note: This may not work correctly on 32-bit machines.
507--
508-- /Pre-release/
509--
510{-# INLINE pollCounts #-}
511pollCounts ::
512 (IsStream t, MonadAsync m)
513 => (a -> Bool)
514 -> (t m Int -> t m Int)
515 -> Fold m Int b
516 -> t m a
517 -> t m a
518pollCounts predicate transf f xs =
519 D.fromStreamD
520 $ D.pollCounts predicate (D.toStreamD . transf . D.fromStreamD) f
521 $ D.toStreamD xs
523-- | Calls the supplied function with the number of elements consumed
524-- every @n@ seconds. The given function is run in a separate thread
525-- until the end of the stream. In case there is an exception in the
526-- stream the thread is killed during the next major GC.
527--
528-- Note: The action is not guaranteed to run if the main thread exits.
529--
530-- @
531-- > delay n = threadDelay (round $ n * 1000000) >> return n
532-- > Stream.toList $ Stream.tapRate 2 (\n -> print $ show n ++ " elements processed") (delay 1 Stream.|: delay 0.5 Stream.|: delay 0.5 Stream.|: Stream.nil)
533-- "2 elements processed"
534-- [1.0,0.5,0.5]
535-- "1 elements processed"
536-- @
537--
538-- Note: This may not work correctly on 32-bit machines.
539--
540-- /Pre-release/
541{-# INLINE tapRate #-}
542tapRate ::
543 (IsStream t, MonadAsync m, MonadCatch m)
544 => Double
545 -> (Int -> m b)
546 -> t m a
547 -> t m a
548tapRate n f xs = D.fromStreamD $ D.tapRate n f $ D.toStreamD xs
550-- | Apply a monadic function to each element flowing through the stream and
551-- discard the results.
552--
553-- @
554-- >>> Stream.drain $ Stream.trace print (Stream.enumerateFromTo 1 2)
555-- 1
556-- 2
557--
558-- @
559--
560-- Compare with 'tap'.
561--
562-- @since 0.7.0
563{-# INLINE trace #-}
564trace :: (IsStream t, MonadAsync m) => (a -> m b) -> t m a -> t m a
565trace f = mapM (\x -> void (f x) >> return x)
567-- | Perform a side effect before yielding each element of the stream and
568-- discard the results.
569--
570-- @
571-- >>> Stream.drain $ Stream.trace_ (print "got here") (Stream.enumerateFromTo 1 2)
572-- "got here"
573-- "got here"
574--
575-- @
576--
577-- Same as 'interspersePrefix_' but always serial.
578--
579-- See also: 'trace'
580--
581-- /Pre-release/
582{-# INLINE trace_ #-}
583trace_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
584trace_ eff = Serial.mapM (\x -> eff >> return x)
586------------------------------------------------------------------------------
587-- Scanning with a Fold
588------------------------------------------------------------------------------
590-- | Scan a stream using the given monadic fold.
591--
592-- >>> Stream.toList $ Stream.takeWhile (< 10) $ Stream.scan Fold.sum (Stream.fromList [1..10])
593-- [0,1,3,6]
594--
595-- @since 0.7.0
596{-# INLINE scan #-}
597scan :: (IsStream t, Monad m) => Fold m a b -> t m a -> t m b
598scan = P.scanOnce
600-- | Postscan a stream using the given monadic fold.
601--
602-- The following example extracts the input stream up to a point where the
603-- running average of elements is no more than 10:
604--
605-- >>> import Data.Maybe (fromJust)
606-- >>> let avg = Fold.teeWith (/) Fold.sum (fmap fromIntegral Fold.length)
607-- >>> :{
608-- Stream.toList
609-- $ Stream.map (fromJust . fst)
610-- $ Stream.takeWhile (\(_,x) -> x <= 10)
611-- $ Stream.postscan (Fold.tee Fold.last avg) (Stream.enumerateFromTo 1.0 100.0)
612-- :}
613-- [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]
614--
615-- @since 0.7.0
616{-# INLINE postscan #-}
617postscan :: (IsStream t, Monad m) => Fold m a b -> t m a -> t m b
618postscan = P.postscanOnce
620------------------------------------------------------------------------------
621-- Scanning - Transformation by Folding
622------------------------------------------------------------------------------
624-- XXX It may be useful to have a version of scan where we can keep the
625-- accumulator independent of the value emitted. So that we do not necessarily
626-- have to keep a value in the accumulator which we are not using. We can pass
627-- an extraction function that will take the accumulator and the current value
628-- of the element and emit the next value in the stream. That will also make it
629-- possible to modify the accumulator after using it. In fact, the step function
630-- can return new accumulator and the value to be emitted. The signature would
631-- be more like mapAccumL. Or we can change the signature of scanx to
632-- accommodate this.
633--
634-- | Strict left scan with an extraction function. Like 'scanl'', but applies a
635-- user supplied extraction function (the third argument) at each step. This is
636-- designed to work with the @foldl@ library. The suffix @x@ is a mnemonic for
637-- extraction.
638--
639-- /Since 0.2.0/
640--
641-- /Since: 0.7.0 (Monad m constraint)/
642{-# DEPRECATED scanx "Please use scanl followed by map instead." #-}
643{-# INLINE scanx #-}
644scanx :: (IsStream t, Monad m) => (x -> a -> x) -> x -> (x -> b) -> t m a -> t m b
645scanx = P.scanlx'
647-- XXX this needs to be concurrent
648-- XXX because of the use of D.cons for appending, scanlM' has quadratic
649-- complexity when iterated over a stream. We should use StreamK style scanlM'
650-- for linear performance on iteration.
651--
652-- | Like 'scanl'' but with a monadic step function and a monadic seed.
653--
654-- /Since: 0.4.0/
655--
656-- /Since: 0.8.0 (signature change)/
657{-# INLINE scanlM' #-}
658scanlM' :: (IsStream t, Monad m) => (b -> a -> m b) -> m b -> t m a -> t m b
659scanlM' step begin m = fromStreamD $ D.scanlM' step begin $ toStreamD m
661-- XXX because of the use of D.cons for appending, scanl' has quadratic
662-- complexity when iterated over a stream. We should use StreamK style scanlM'
663-- for linear performance on iteration.
665-- | Strict left scan. Like 'map', 'scanl'' too is a one to one transformation,
666-- however it adds an extra element.
667--
668-- @
669-- >>> Stream.toList $ Stream.scanl' (+) 0 $ fromList [1,2,3,4]
670-- [0,1,3,6,10]
671--
672-- @
673--
674-- @
675-- >>> Stream.toList $ Stream.scanl' (flip (:)) [] $ Stream.fromList [1,2,3,4]
676-- [[],[1],[2,1],[3,2,1],[4,3,2,1]]
677--
678-- @
679--
680-- The output of 'scanl'' is the initial value of the accumulator followed by
681-- all the intermediate steps and the final result of 'foldl''.
682--
683-- By streaming the accumulated state after each fold step, we can share the
684-- state across multiple stages of stream composition. Each stage can modify or
685-- extend the state, do some processing with it and emit it for the next stage,
686-- thus modularizing the stream processing. This can be useful in
687-- stateful or event-driven programming.
688--
689-- Consider the following monolithic example, computing the sum and the product
690-- of the elements in a stream in one go using a @foldl'@:
691--
692-- @
693-- >>> Stream.foldl' (\(s, p) x -> (s + x, p * x)) (0,1) $ Stream.fromList [1,2,3,4]
694-- (10,24)
695--
696-- @
697--
698-- Using @scanl'@ we can make it modular by computing the sum in the first
699-- stage and passing it down to the next stage for computing the product:
700--
701-- @
702-- >>> :{
703-- Stream.foldl' (\(_, p) (s, x) -> (s, p * x)) (0,1)
704-- $ Stream.scanl' (\(s, _) x -> (s + x, x)) (0,1)
705-- $ Stream.fromList [1,2,3,4]
706-- :}
707-- (10,24)
708--
709-- @
710--
711-- IMPORTANT: 'scanl'' evaluates the accumulator to WHNF. To avoid building
712-- lazy expressions inside the accumulator, it is recommended that a strict
713-- data structure is used for accumulator.
714--
715-- See also: 'usingStateT'
716--
717-- @since 0.2.0
718{-# INLINE scanl' #-}
719scanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
720scanl' step z m = fromStreamS $ S.scanl' step z $ toStreamS m
722-- | Like 'scanl'' but does not stream the initial value of the accumulator.
723--
724-- > postscanl' f z xs = Stream.drop 1 $ Stream.scanl' f z xs
725--
726-- @since 0.7.0
727{-# INLINE postscanl' #-}
728postscanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
729postscanl' step z m = fromStreamD $ D.postscanl' step z $ toStreamD m
731-- XXX prescanl does not sound very useful, enable only if there is a
732-- compelling use case.
733--
734-- | Like scanl' but does not stream the final value of the accumulator.
735--
736-- /Pre-release/
737{-# INLINE prescanl' #-}
738prescanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
739prescanl' step z m = fromStreamD $ D.prescanl' step z $ toStreamD m
741-- XXX this needs to be concurrent
742-- | Like prescanl' but with a monadic step function and a monadic seed.
743--
744-- /Pre-release/
745{-# INLINE prescanlM' #-}
746prescanlM' :: (IsStream t, Monad m) => (b -> a -> m b) -> m b -> t m a -> t m b
747prescanlM' step z m = fromStreamD $ D.prescanlM' step z $ toStreamD m
749-- XXX this needs to be concurrent
750-- | Like 'scanl1'' but with a monadic step function.
751--
752-- @since 0.6.0
753{-# INLINE scanl1M' #-}
754scanl1M' :: (IsStream t, Monad m) => (a -> a -> m a) -> t m a -> t m a
755scanl1M' step m = fromStreamD $ D.scanl1M' step $ toStreamD m
757-- | Like 'scanl'' but for a non-empty stream. The first element of the stream
758-- is used as the initial value of the accumulator. Does nothing if the stream
759-- is empty.
760--
761-- @
762-- >>> Stream.toList $ Stream.scanl1' (+) $ fromList [1,2,3,4]
763-- [1,3,6,10]
764--
765-- @
766--
767-- @since 0.6.0
768{-# INLINE scanl1' #-}
769scanl1' :: (IsStream t, Monad m) => (a -> a -> a) -> t m a -> t m a
770scanl1' step m = fromStreamD $ D.scanl1' step $ toStreamD m
772------------------------------------------------------------------------------
773-- Filtering
774------------------------------------------------------------------------------
776-- | Modify a @t m a -> t m a@ stream transformation that accepts a predicate
777-- @(a -> b)@ to accept @((s, a) -> b)@ instead, provided a transformation @t m
778-- a -> t m (s, a)@. Convenient to filter with index or time.
779--
780-- @
781-- filterWithIndex = with indexed filter
782-- filterWithAbsTime = with timestamped filter
783-- filterWithRelTime = with timeIndexed filter
784-- @
785--
786-- /Pre-release/
787{-# INLINE with #-}
788with :: forall (t :: (Type -> Type) -> Type -> Type) m a b s. Functor (t m) =>
789 (t m a -> t m (s, a))
790 -> (((s, a) -> b) -> t m (s, a) -> t m (s, a))
791 -> (((s, a) -> b) -> t m a -> t m a)
792with f comb g = fmap snd . comb g . f
794-- | Include only those elements that pass a predicate.
795--
796-- @since 0.1.0
797{-# INLINE filter #-}
798#if __GLASGOW_HASKELL__ != 802
799-- GHC 8.2.2 crashes with this code, when used with "stack"
800filter :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m a
801filter p m = fromStreamS $ S.filter p $ toStreamS m
802#else
803filter :: IsStream t => (a -> Bool) -> t m a -> t m a
804filter = K.filter
805#endif
807-- | Same as 'filter' but with a monadic predicate.
808--
809-- @since 0.4.0
810{-# INLINE filterM #-}
811filterM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
812filterM p m = fromStreamD $ D.filterM p $ toStreamD m
814-- | Drop repeated elements that are adjacent to each other using the supplied
815-- comparison function.
816--
817-- @uniq = uniqBy (==)
818--
819-- To strip duplicate path separators:
820--
821-- @
822-- f x y = x == '/' && x == y
823-- Stream.toList $ Stream.uniqBy f $ Stream.fromList "//a//b"
824-- "/a/b"
825-- @
826--
827-- Space: @O(1)@
828--
829-- See also: 'nubBy'.
830--
831-- /Pre-release/
832--
833{-# INLINE uniqBy #-}
834uniqBy :: (IsStream t, Monad m, Functor (t m)) =>
835 (a -> a -> Bool) -> t m a -> t m a
836uniqBy eq =
837 catMaybes . rollingMap (\x y -> if x `eq` y then Nothing else Just y)
839-- | Drop repeated elements that are adjacent to each other.
840--
841-- @since 0.6.0
842{-# INLINE uniq #-}
843uniq :: (Eq a, IsStream t, Monad m) => t m a -> t m a
844uniq = fromStreamD . D.uniq . toStreamD
846-- | Strip all leading and trailing occurrences of an element passing a
847-- predicate and make all other consecutive occurrences uniq.
848--
849-- @
850-- prune p = dropWhileAround p $ uniqBy (x y -> p x && p y)
851-- @
852--
853-- @
854-- > Stream.prune isSpace (Stream.fromList " hello world! ")
855-- "hello world!"
856--
857-- @
858--
859-- Space: @O(1)@
860--
861-- /Unimplemented/
862{-# INLINE prune #-}
863prune ::
864 -- (IsStream t, Monad m, Eq a) =>
865 (a -> Bool) -> t m a -> t m a
866prune = error "Not implemented yet!"
868-- Possible implementation:
869-- @repeated =
870-- Stream.catMaybes . Stream.parseMany (Parser.groupBy (==) Fold.repeated)@
871--
872-- 'Fold.repeated' should return 'Just' when repeated, and 'Nothing' for a
873-- single element.
874--
875-- | Emit only repeated elements, once.
876--
877-- /Unimplemented/
878repeated :: -- (IsStream t, Monad m, Eq a) =>
879 t m a -> t m a
880repeated = undefined
882-- We can have more efficient implementations for nubOrd and nubInt by using
883-- Set and IntSet to find/remove duplication. For Hashable we can use a
884-- hashmap. Use rewrite rules to specialize to more efficient impls.
885--
886-- | Drop repeated elements anywhere in the stream.
887--
888-- /Caution: not scalable for infinite streams/
889--
890-- /See also: nubWindowBy/
891--
892-- /Unimplemented/
893--
894{-# INLINE nubBy #-}
895nubBy :: -- (IsStream t, Monad m) =>
896 (a -> a -> Bool) -> t m a -> t m a
897nubBy = undefined -- fromStreamD . D.nubBy . toStreamD
899-- | Drop repeated elements within the specified tumbling window in the stream.
900--
901-- @nubBy = nubWindowBy maxBound@
902--
903-- /Unimplemented/
904--
905{-# INLINE nubWindowBy #-}
906nubWindowBy :: -- (IsStream t, Monad m) =>
907 Int -> (a -> a -> Bool) -> t m a -> t m a
908nubWindowBy = undefined -- fromStreamD . D.nubWithinBy . toStreamD
910-- | Deletes the first occurrence of the element in the stream that satisfies
911-- the given equality predicate.
912--
913-- @
914-- >>> Stream.toList $ Stream.deleteBy (==) 3 $ Stream.fromList [1,3,3,5]
915-- [1,3,5]
916--
917-- @
918--
919-- @since 0.6.0
920{-# INLINE deleteBy #-}
921deleteBy :: (IsStream t, Monad m) => (a -> a -> Bool) -> a -> t m a -> t m a
922deleteBy cmp x m = fromStreamS $ S.deleteBy cmp x (toStreamS m)
924------------------------------------------------------------------------------
925-- Lossy Buffering
926------------------------------------------------------------------------------
928-- XXX We could use 'maxBuffer Block/Drop/Rotate/Sample' instead. However we
929-- may want to have the evaluation rate independent of the sampling rate. To
930-- support that we can decouple evaluation and sampling in independent stages.
931-- The sampling stage would strictly evaluate and sample, the evaluation stage
932-- would control the evaluation rate.
934-- | Evaluate the input stream continuously and keep only the oldest @n@
935-- elements in the buffer, discard the new ones when the buffer is full. When
936-- the output stream is evaluated it consumes the values from the buffer in a
937-- FIFO manner.
938--
939-- /Unimplemented/
940--
941{-# INLINE sampleOld #-}
942sampleOld :: -- (IsStream t, Monad m) =>
943 Int -> t m a -> t m a
944sampleOld = undefined
946-- | Evaluate the input stream continuously and keep only the latest @n@
947-- elements in a ring buffer, keep discarding the older ones to make space for
948-- the new ones. When the output stream is evaluated it consumes the values
949-- from the buffer in a FIFO manner.
950--
951-- /Unimplemented/
952--
953{-# INLINE sampleNew #-}
954sampleNew :: -- (IsStream t, Monad m) =>
955 Int -> t m a -> t m a
956sampleNew = undefined
958-- | Like 'sampleNew' but samples at uniform intervals to match the consumer
959-- rate. Note that 'sampleNew' leads to non-uniform sampling depending on the
960-- consumer pattern.
961--
962-- /Unimplemented/
963--
964{-# INLINE sampleRate #-}
965sampleRate :: -- (IsStream t, Monad m) =>
966 Double -> t m a -> t m a
967sampleRate = undefined
969------------------------------------------------------------------------------
970-- Trimming
971------------------------------------------------------------------------------
973-- | Same as 'takeWhile' but with a monadic predicate.
974--
975-- @since 0.4.0
976{-# INLINE takeWhileM #-}
977takeWhileM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
978takeWhileM p m = fromStreamD $ D.takeWhileM p $ toStreamD m
980-- See the lastN fold for impl hints. Use a Data.Array based ring buffer.
981--
982-- takeLast n = Stream.concatM . fmap Array.toStream . fold Fold.lastN
983--
984-- | Take @n@ elements at the end of the stream.
985--
986-- O(n) space, where n is the number elements taken.
987--
988-- /Unimplemented/
989{-# INLINE takeLast #-}
990takeLast :: -- (IsStream t, Monad m) =>
991 Int -> t m a -> t m a
992takeLast = undefined -- fromStreamD $ D.takeLast n $ toStreamD m
994-- | Take time interval @i@ seconds at the end of the stream.
995--
996-- O(n) space, where n is the number elements taken.
997--
998-- /Unimplemented/
999{-# INLINE takeLastInterval #-}
1000takeLastInterval :: -- (IsStream t, Monad m) =>
1001 Double -> t m a -> t m a
1002takeLastInterval = undefined -- fromStreamD $ D.takeLast n $ toStreamD m
1004-- | Take all consecutive elements at the end of the stream for which the
1005-- predicate is true.
1007-- O(n) space, where n is the number elements taken.
1009-- /Unimplemented/
1010{-# INLINE takeWhileLast #-}
1011takeWhileLast :: -- (IsStream t, Monad m) =>
1012 (a -> Bool) -> t m a -> t m a
1013takeWhileLast = undefined -- fromStreamD $ D.takeWhileLast n $ toStreamD m
1015-- | Like 'takeWhile' and 'takeWhileLast' combined.
1017-- O(n) space, where n is the number elements taken from the end.
1019-- /Unimplemented/
1020{-# INLINE takeWhileAround #-}
1021takeWhileAround :: -- (IsStream t, Monad m) =>
1022 (a -> Bool) -> t m a -> t m a
1023takeWhileAround = undefined -- fromStreamD $ D.takeWhileAround n $ toStreamD m
1025-- | @takeInterval duration@ yields stream elements upto specified time
1026-- @duration@. The duration starts when the stream is evaluated for the first
1027-- time, before the first element is yielded. The time duration is checked
1028-- before generating each element, if the duration has expired the stream
1029-- stops.
1031-- The total time taken in executing the stream is guaranteed to be /at least/
1032-- @duration@, however, because the duration is checked before generating an
1033-- element, the upper bound is indeterminate and depends on the time taken in
1034-- generating and processing the last element.
1036-- No element is yielded if the duration is zero. At least one element is
1037-- yielded if the duration is non-zero.
1039-- /Pre-release/
1041{-# INLINE takeInterval #-}
1042takeInterval ::(MonadIO m, IsStream t, TimeUnit64 d) => d -> t m a -> t m a
1043takeInterval d = fromStreamD . D.takeByTime d . toStreamD
1045-- | Drop elements in the stream as long as the predicate succeeds and then
1046-- take the rest of the stream.
1048-- @since 0.1.0
1049{-# INLINE dropWhile #-}
1050dropWhile :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m a
1051dropWhile p m = fromStreamS $ S.dropWhile p $ toStreamS m
1053-- | Same as 'dropWhile' but with a monadic predicate.
1055-- @since 0.4.0
1056{-# INLINE dropWhileM #-}
1057dropWhileM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
1058dropWhileM p m = fromStreamD $ D.dropWhileM p $ toStreamD m
1060-- | @dropInterval duration@ drops stream elements until specified @duration@ has
1061-- passed. The duration begins when the stream is evaluated for the first
1062-- time. The time duration is checked /after/ generating a stream element, the
1063-- element is yielded if the duration has expired otherwise it is dropped.
1065-- The time elapsed before starting to generate the first element is /at most/
1066-- @duration@, however, because the duration expiry is checked after the
1067-- element is generated, the lower bound is indeterminate and depends on the
1068-- time taken in generating an element.
1070-- All elements are yielded if the duration is zero.
1072-- /Pre-release/
1074{-# INLINE dropInterval #-}
1075dropInterval ::(MonadIO m, IsStream t, TimeUnit64 d) => d -> t m a -> t m a
1076dropInterval d = fromStreamD . D.dropByTime d . toStreamD
1078-- | Drop @n@ elements at the end of the stream.
1080-- O(n) space, where n is the number elements dropped.
1082-- /Unimplemented/
1083{-# INLINE dropLast #-}
1084dropLast :: -- (IsStream t, Monad m) =>
1085 Int -> t m a -> t m a
1086dropLast = undefined -- fromStreamD $ D.dropLast n $ toStreamD m
1088-- | Drop time interval @i@ seconds at the end of the stream.
1090-- O(n) space, where n is the number elements dropped.
1092-- /Unimplemented/
1093{-# INLINE dropLastInterval #-}
1094dropLastInterval :: -- (IsStream t, Monad m) =>
1095 Int -> t m a -> t m a
1096dropLastInterval = undefined
1098-- | Drop all consecutive elements at the end of the stream for which the
1099-- predicate is true.
1101-- O(n) space, where n is the number elements dropped.
1103-- /Unimplemented/
1104{-# INLINE dropWhileLast #-}
1105dropWhileLast :: -- (IsStream t, Monad m) =>
1106 (a -> Bool) -> t m a -> t m a
1107dropWhileLast = undefined -- fromStreamD $ D.dropWhileLast n $ toStreamD m
1109-- | Like 'dropWhile' and 'dropWhileLast' combined.
1111-- O(n) space, where n is the number elements dropped from the end.
1113-- /Unimplemented/
1114{-# INLINE dropWhileAround #-}
1115dropWhileAround :: -- (IsStream t, Monad m) =>
1116 (a -> Bool) -> t m a -> t m a
1117dropWhileAround = undefined -- fromStreamD $ D.dropWhileAround n $ toStreamD m
1119------------------------------------------------------------------------------
1120-- Inserting Elements
1121------------------------------------------------------------------------------
1123-- | @insertBy cmp elem stream@ inserts @elem@ before the first element in
1124-- @stream@ that is less than @elem@ when compared using @cmp@.
1126-- @
1127-- insertBy cmp x = 'mergeBy' cmp ('fromPure' x)
1128-- @
1130-- @
1131-- >>> Stream.toList $ Stream.insertBy compare 2 $ Stream.fromList [1,3,5]
1132-- [1,2,3,5]
1134-- @
1136-- @since 0.6.0
1137{-# INLINE insertBy #-}
1138insertBy ::
1139 (IsStream t, Monad m) => (a -> a -> Ordering) -> a -> t m a -> t m a
1140insertBy cmp x m = fromStreamS $ S.insertBy cmp x (toStreamS m)
1142-- | Insert a pure value between successive elements of a stream.
1144-- >>> Stream.toList $ Stream.intersperse ',' $ Stream.fromList "hello"
1145-- "h,e,l,l,o"
1147-- @since 0.7.0
1148{-# INLINE intersperse #-}
1149intersperse :: (IsStream t, MonadAsync m) => a -> t m a -> t m a
1150intersperse a = fromStreamS . S.intersperse a . toStreamS
1152-- | Insert a side effect before consuming an element of a stream except the
1153-- first one.
1155-- >>> Stream.drain $ Stream.trace putChar $ Stream.intersperseM_ (putChar '.') $ Stream.fromList "hello"
1156-- h.e.l.l.o
1158-- /Pre-release/
1159{-# INLINE intersperseM_ #-}
1160intersperseM_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
1161intersperseM_ m = fromStreamD . D.intersperseM_ m . toStreamD
1163-- | Intersperse a monadic action into the input stream after every @n@
1164-- elements.
1166-- @
1167-- > Stream.toList $ Stream.intersperseBySpan 2 (return ',') $ Stream.fromList "hello"
1168-- "he,ll,o"
1170-- @
1172-- /Unimplemented/
1173{-# INLINE intersperseBySpan #-}
1174intersperseBySpan :: -- IsStream t =>
1175 Int -> m a -> t m a -> t m a
1176intersperseBySpan _n _f _xs = undefined
1178-- | Insert an effect and its output after consuming an element of a stream.
1180-- >>> Stream.toList $ Stream.trace putChar $ intersperseSuffix (putChar '.' >> return ',') $ Stream.fromList "hello"
1181-- h.,e.,l.,l.,o.,"h,e,l,l,o,"
1183-- /Pre-release/
1184{-# INLINE intersperseSuffix #-}
1185intersperseSuffix :: (IsStream t, Monad m) => m a -> t m a -> t m a
1186intersperseSuffix m = fromStreamD . D.intersperseSuffix m . toStreamD
1188-- | Insert a side effect after consuming an element of a stream.
1190-- @
1191-- >>> Stream.mapM_ putChar $ Stream.intersperseSuffix_ (threadDelay 1000000) $ Stream.fromList "hello"
1192-- hello
1194-- @
1196-- /Pre-release/
1198{-# INLINE intersperseSuffix_ #-}
1199intersperseSuffix_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
1200intersperseSuffix_ m = fromStreamD . D.intersperseSuffix_ m . toStreamD
1202-- XXX Use an offset argument, like tapOffsetEvery
1204-- | Like 'intersperseSuffix' but intersperses an effectful action into the
1205-- input stream after every @n@ elements and after the last element.
1207-- >>> Stream.toList $ Stream.intersperseSuffixBySpan 2 (return ',') $ Stream.fromList "hello"
1208-- "he,ll,o,"
1210-- /Pre-release/
1212{-# INLINE intersperseSuffixBySpan #-}
1213intersperseSuffixBySpan :: (IsStream t, Monad m)
1214 => Int -> m a -> t m a -> t m a
1215intersperseSuffixBySpan n eff =
1216 fromStreamD . D.intersperseSuffixBySpan n eff . toStreamD
1218-- | Insert a side effect before consuming an element of a stream.
1220-- >>> Stream.toList $ Stream.trace putChar $ Stream.interspersePrefix_ (putChar '.' >> return ',') $ Stream.fromList "hello"
1221-- .h.e.l.l.o"hello"
1223-- Same as 'trace_' but may be concurrent.
1225-- /Concurrent/
1227-- /Pre-release/
1229{-# INLINE interspersePrefix_ #-}
1230interspersePrefix_ :: (IsStream t, MonadAsync m) => m b -> t m a -> t m a
1231interspersePrefix_ m = mapM (\x -> void m >> return x)
1233------------------------------------------------------------------------------
1234-- Inserting Time
1235------------------------------------------------------------------------------
1237-- Note: delay must be serial.
1239-- | Introduce a delay of specified seconds before consuming an element of the
1240-- stream except the first one.
1242-- >>> Stream.mapM_ print $ Stream.timestamped $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
1243-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),1)
1244-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),2)
1245-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),3)
1247-- @since 0.8.0
1249{-# INLINE delay #-}
1250delay :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
1251delay n = intersperseM_ $ liftIO $ threadDelay $ round $ n * 1000000
1253-- Note: delay must be serial.
1255-- | Introduce a delay of specified seconds after consuming an element of a
1256-- stream.
1258-- >>> Stream.mapM_ print $ Stream.timestamped $ Stream.delayPost 1 $ Stream.enumerateFromTo 1 3
1259-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),1)
1260-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),2)
1261-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),3)
1263-- /Pre-release/
1265{-# INLINE delayPost #-}
1266delayPost :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
1267delayPost n = intersperseSuffix_ $ liftIO $ threadDelay $ round $ n * 1000000
1269-- Note: delay must be serial, that's why 'trace_' is used.
1271-- | Introduce a delay of specified seconds before consuming an element of a
1272-- stream.
1274-- >>> Stream.mapM_ print $ Stream.timestamped $ Stream.delayPre 1 $ Stream.enumerateFromTo 1 3
1275-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),1)
1276-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),2)
1277-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),3)
1279-- /Pre-release/
1281{-# INLINE delayPre #-}
1282delayPre :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
1283delayPre n = trace_ $ liftIO $ threadDelay $ round $ n * 1000000
1285------------------------------------------------------------------------------
1286-- Reorder in sequence
1287------------------------------------------------------------------------------
1289-- | Buffer until the next element in sequence arrives. The function argument
1290-- determines the difference in sequence numbers. This could be useful in
1291-- implementing sequenced streams, for example, TCP reassembly.
1293-- /Unimplemented/
1295{-# INLINE reassembleBy #-}
1296reassembleBy
1297 :: -- (IsStream t, Monad m) =>
1298 Fold m a b
1299 -> (a -> a -> Int)
1300 -> t m a
1301 -> t m b
1302reassembleBy = undefined
1304------------------------------------------------------------------------------
1305-- Position Indexing
1306------------------------------------------------------------------------------
1308-- |
1309-- > indexed = Stream.postscanl' (\(i, _) x -> (i + 1, x)) (-1,undefined)
1310-- > indexed = Stream.zipWith (,) (Stream.enumerateFrom 0)
1312-- Pair each element in a stream with its index, starting from index 0.
1314-- >>> Stream.toList $ Stream.indexed $ Stream.fromList "hello"
1315-- [(0,'h'),(1,'e'),(2,'l'),(3,'l'),(4,'o')]
1317-- @since 0.6.0
1318{-# INLINE indexed #-}
1319indexed :: (IsStream t, Monad m) => t m a -> t m (Int, a)
1320indexed = fromStreamD . D.indexed . toStreamD
1322-- |
1323-- > indexedR n = Stream.postscanl' (\(i, _) x -> (i - 1, x)) (n + 1,undefined)
1324-- > indexedR n = Stream.zipWith (,) (Stream.enumerateFromThen n (n - 1))
1326-- Pair each element in a stream with its index, starting from the
1327-- given index @n@ and counting down.
1329-- >>> Stream.toList $ Stream.indexedR 10 $ Stream.fromList "hello"
1330-- [(10,'h'),(9,'e'),(8,'l'),(7,'l'),(6,'o')]
1332-- @since 0.6.0
1333{-# INLINE indexedR #-}
1334indexedR :: (IsStream t, Monad m) => Int -> t m a -> t m (Int, a)
1335indexedR n = fromStreamD . D.indexedR n . toStreamD
1337-------------------------------------------------------------------------------
1338-- Time Indexing
1339-------------------------------------------------------------------------------
1341-- Note: The timestamp stream must be the second stream in the zip so that the
1342-- timestamp is generated after generating the stream element and not before.
1343-- If we do not do that then the following example will generate the same
1344-- timestamp for first two elements:
1346-- Stream.mapM_ print $ Stream.timestamped $ Stream.delay $ Stream.enumerateFromTo 1 3
1348-- | Pair each element in a stream with an absolute timestamp, using a clock of
1349-- specified granularity. The timestamp is generated just before the element
1350-- is consumed.
1352-- >>> Stream.mapM_ print $ Stream.timestampWith 0.01 $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
1353-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),1)
1354-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),2)
1355-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),3)
1357-- /Pre-release/
1359{-# INLINE timestampWith #-}
1360timestampWith :: (IsStream t, MonadAsync m, Functor (t m))
1361 => Double -> t m a -> t m (AbsTime, a)
1362timestampWith g stream = Z.zipWith (flip (,)) stream (absTimesWith g)
1364-- TBD: check performance vs a custom implementation without using zipWith.
1366-- /Pre-release/
1368{-# INLINE timestamped #-}
1369timestamped :: (IsStream t, MonadAsync m, Functor (t m))
1370 => t m a -> t m (AbsTime, a)
1371timestamped = timestampWith 0.01
1373-- | Pair each element in a stream with relative times starting from 0, using a
1374-- clock with the specified granularity. The time is measured just before the
1375-- element is consumed.
1377-- >>> Stream.mapM_ print $ Stream.timeIndexWith 0.01 $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
1378-- (RelTime64 (NanoSecond64 ...),1)
1379-- (RelTime64 (NanoSecond64 ...),2)
1380-- (RelTime64 (NanoSecond64 ...),3)
1382-- /Pre-release/
1384{-# INLINE timeIndexWith #-}
1385timeIndexWith :: (IsStream t, MonadAsync m, Functor (t m))
1386 => Double -> t m a -> t m (RelTime64, a)
1387timeIndexWith g stream = Z.zipWith (flip (,)) stream (relTimesWith g)
1389-- | Pair each element in a stream with relative times starting from 0, using a
1390-- 10 ms granularity clock. The time is measured just before the element is
1391-- consumed.
1393-- >>> Stream.mapM_ print $ Stream.timeIndexed $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
1394-- (RelTime64 (NanoSecond64 ...),1)
1395-- (RelTime64 (NanoSecond64 ...),2)
1396-- (RelTime64 (NanoSecond64 ...),3)
1398-- /Pre-release/
1400{-# INLINE timeIndexed #-}
1401timeIndexed :: (IsStream t, MonadAsync m, Functor (t m))
1402 => t m a -> t m (RelTime64, a)
1403timeIndexed = timeIndexWith 0.01
1405------------------------------------------------------------------------------
1406-- Searching
1407------------------------------------------------------------------------------
1409-- | Find all the indices where the value of the element in the stream is equal
1410-- to the given value.
1412-- > elemIndices a = findIndices (== a)
1414-- @since 0.5.0
1415{-# INLINE elemIndices #-}
1416elemIndices :: (IsStream t, Eq a, Monad m) => a -> t m a -> t m Int
1417elemIndices a = findIndices (== a)
1419------------------------------------------------------------------------------
1420-- Rolling map
1421------------------------------------------------------------------------------
1423-- XXX this is not a one-to-one map so calling it map may not be right.
1424-- We can perhaps call it zipWithTail or rollWith.
1426-- | Apply a function on every two successive elements of a stream. If the
1427-- stream consists of a single element the output is an empty stream.
1429-- This is the stream equivalent of the list idiom @zipWith f xs (tail xs)@.
1431-- /Pre-release/
1433{-# INLINE rollingMap #-}
1434rollingMap :: (IsStream t, Monad m) => (a -> a -> b) -> t m a -> t m b
1435rollingMap f m = fromStreamD $ D.rollingMap f $ toStreamD m
1437-- | Like 'rollingMap' but with an effectful map function.
1439-- /Pre-release/
1441{-# INLINE rollingMapM #-}
1442rollingMapM :: (IsStream t, Monad m) => (a -> a -> m b) -> t m a -> t m b
1443rollingMapM f m = fromStreamD $ D.rollingMapM f $ toStreamD m
1445------------------------------------------------------------------------------
1446-- Maybe Streams
1447------------------------------------------------------------------------------
1449-- | Map a 'Maybe' returning function to a stream, filter out the 'Nothing'
1450-- elements, and return a stream of values extracted from 'Just'.
1452-- Equivalent to:
1454-- @
1455-- mapMaybe f = Stream.map 'fromJust' . Stream.filter 'isJust' . Stream.map f
1456-- @
1458-- @since 0.3.0
1459{-# INLINE mapMaybe #-}
1460mapMaybe :: (IsStream t, Monad m) => (a -> Maybe b) -> t m a -> t m b
1461mapMaybe f m = fromStreamS $ S.mapMaybe f $ toStreamS m
1463-- | Like 'mapMaybe' but maps a monadic function.
1465-- Equivalent to:
1467-- @
1468-- mapMaybeM f = Stream.map 'fromJust' . Stream.filter 'isJust' . Stream.mapM f
1469-- @
1471-- /Concurrent (do not use with 'fromParallel' on infinite streams)/
1473-- @since 0.3.0
1474{-# INLINE_EARLY mapMaybeM #-}
1475mapMaybeM :: (IsStream t, MonadAsync m, Functor (t m))
1476 => (a -> m (Maybe b)) -> t m a -> t m b
1477mapMaybeM f = fmap fromJust . filter isJust . K.mapM f
1479{-# RULES "mapMaybeM serial" mapMaybeM = mapMaybeMSerial #-}
1480{-# INLINE mapMaybeMSerial #-}
1481mapMaybeMSerial :: Monad m => (a -> m (Maybe b)) -> SerialT m a -> SerialT m b
1482mapMaybeMSerial f m = fromStreamD $ D.mapMaybeM f $ toStreamD m
1484-- | In a stream of 'Maybe's, discard 'Nothing's and unwrap 'Just's.
1486-- /Pre-release/
1488catMaybes :: (IsStream t, Monad m, Functor (t m)) => t m (Maybe a) -> t m a
1489catMaybes = fmap fromJust . filter isJust
1491------------------------------------------------------------------------------
1492-- Either streams
1493------------------------------------------------------------------------------
1495-- | Discard 'Right's and unwrap 'Left's in an 'Either' stream.
1497-- /Pre-release/
1499lefts :: (IsStream t, Monad m, Functor (t m)) => t m (Either a b) -> t m a
1500lefts = fmap (fromLeft undefined) . filter isLeft
1502-- | Discard 'Left's and unwrap 'Right's in an 'Either' stream.
1504-- /Pre-release/
1506rights :: (IsStream t, Monad m, Functor (t m)) => t m (Either a b) -> t m b
1507rights = fmap (fromRight undefined) . filter isRight
1509------------------------------------------------------------------------------
1510-- Concurrent Application
1511------------------------------------------------------------------------------
1513-- | Parallel transform application operator; applies a stream transformation
1514-- function @t m a -> t m b@ to a stream @t m a@ concurrently; the input stream
1515-- is evaluated asynchronously in an independent thread yielding elements to a
1516-- buffer and the transformation function runs in another thread consuming the
1517-- input from the buffer. '|$' is just like regular function application
1518-- operator '$' except that it is concurrent.
1520-- If you read the signature as @(t m a -> t m b) -> (t m a -> t m b)@ you can
1521-- look at it as a transformation that converts a transform function to a
1522-- buffered concurrent transform function.
1524-- The following code prints a value every second even though each stage adds a
1525-- 1 second delay.
1528-- >>> :{
1529-- Stream.drain $
1530-- Stream.mapM (\x -> threadDelay 1000000 >> print x)
1531-- |$ Stream.replicateM 3 (threadDelay 1000000 >> return 1)
1532-- :}
1533-- 1
1534-- 1
1535-- 1
1537-- /Concurrent/
1539-- /Since: 0.3.0 ("Streamly")/
1541-- @since 0.8.0
1542{-# INLINE (|$) #-}
1543(|$) :: (IsStream t, MonadAsync m) => (t m a -> t m b) -> (t m a -> t m b)
1544-- (|$) f = f . Async.mkAsync
1545(|$) f = f . Par.mkParallel
1547infixr 0 |$
1549-- | Same as '|$'.
1551-- /Internal/
1553{-# INLINE applyAsync #-}
1554applyAsync :: (IsStream t, MonadAsync m)
1555 => (t m a -> t m b) -> (t m a -> t m b)
1556applyAsync = (|$)
1558-- | Same as '|$' but with arguments reversed.
1560-- (|&) = flip (|$)
1562-- /Concurrent/
1564-- /Since: 0.3.0 ("Streamly")/
1566-- @since 0.8.0
1567{-# INLINE (|&) #-}
1568(|&) :: (IsStream t, MonadAsync m) => t m a -> (t m a -> t m b) -> t m b
1569x |& f = f |$ x
1571infixl 1 |&