on 7bf60ff help sign in
1588 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
167 , both
169 -- * Concurrent Evaluation
170 -- ** Concurrent Pipelines
171 -- | Run streaming stages concurrently.
173 , Par.mkParallel
174 , applyAsync
175 , (|$)
176 , (|&)
178 -- ** Concurrency Control
179 , maxThreads
181 -- ** Buffering and Sampling
182 -- | Evaluate strictly using a buffer of results. When the buffer becomes
183 -- full we can block, drop the new elements, drop the oldest element and
184 -- insert the new at the end or keep dropping elements uniformly to match
185 -- the rate of the consumer.
186 , maxBuffer
187 , sampleOld
188 , sampleNew
189 , sampleRate
191 -- ** Rate Limiting
192 -- | Evaluate the stream at uniform intervals to maintain a specified
193 -- evaluation rate.
194 , Rate (..)
195 , rate
196 , avgRate
197 , minRate
198 , maxRate
199 , constRate
201 -- * Diagnostics
202 , inspectMode
204 -- * Deprecated
205 , scanx
206 )
207where
209#include "inline.hs"
211import Control.Concurrent (threadDelay)
212import Control.Monad (void)
213import Control.Monad.Catch (MonadCatch)
214import Control.Monad.IO.Class (MonadIO(..))
215import Control.Monad.Trans.Class (MonadTrans(..))
216import Data.Either (isLeft, isRight)
217import Data.Kind (Type)
218import Data.Maybe (isJust, fromJust)
219import Streamly.Internal.BaseCompat (fromLeft, fromRight)
220import Streamly.Internal.Data.Fold.Type (Fold (..))
221import Streamly.Internal.Data.Pipe.Type (Pipe (..))
222import Streamly.Internal.Data.Stream.IsStream.Combinators
223 ( inspectMode, maxBuffer, maxThreads, rate, avgRate, minRate
224 , maxRate, constRate)
225import Streamly.Internal.Data.Stream.IsStream.Common
226 ( absTimesWith
227 , drop
228 , findIndices
229 , postscanlM'
230 , relTimesWith
231 , reverse
232 , reverse'
233 , scanlMAfter'
234 , smapM
235 , take
236 , takeWhile
237 , interjectSuffix
238 , intersperseM
239 )
240import Streamly.Internal.Data.Stream.Prelude (fromStreamS, toStreamS)
241import Streamly.Internal.Data.Stream.Serial (SerialT)
242import Streamly.Internal.Data.Stream.StreamD (fromStreamD, toStreamD)
243import Streamly.Internal.Data.Stream.StreamK (IsStream)
244import Streamly.Internal.Data.SVar (MonadAsync, Rate(..))
245import Streamly.Internal.Data.Time.Units (TimeUnit64, AbsTime, RelTime64)
247import qualified Streamly.Internal.Data.Fold as FL
248import qualified Streamly.Internal.Data.Stream.Parallel as Par
249import qualified Streamly.Internal.Data.Stream.Prelude as P
250import qualified Streamly.Internal.Data.Stream.Serial as Serial
251import qualified Streamly.Internal.Data.Stream.StreamD as D
252import qualified Streamly.Internal.Data.Stream.StreamK as K
253import qualified Streamly.Internal.Data.Stream.Zip as Z
254#ifdef USE_STREAMK_ONLY
255import qualified Streamly.Internal.Data.Stream.StreamK as S
256#else
257import qualified Streamly.Internal.Data.Stream.StreamD as S
258#endif
260import Prelude hiding
261 ( filter, drop, dropWhile, take, takeWhile, foldr, map, mapM, sequence
262 , reverse, foldr1 , scanl, scanl1)
264--
265-- $setup
266-- >>> :m
267-- >>> import Control.Concurrent (threadDelay)
268-- >>> import Data.Function ((&))
269-- >>> import Streamly.Prelude ((|$))
270-- >>> import Prelude hiding ( filter, drop, dropWhile, take, takeWhile, foldr, map, mapM, sequence, reverse, foldr1 , scanl, scanl1)
271-- >>> import qualified Streamly.Prelude as Stream
272-- >>> import Streamly.Internal.Data.Stream.IsStream as Stream
273-- >>> import qualified Streamly.Data.Fold as Fold
274-- >>> import qualified Streamly.Internal.Data.Fold as Fold
276------------------------------------------------------------------------------
277-- Piping
278------------------------------------------------------------------------------
280-- | Use a 'Pipe' to transform a stream.
281--
282-- /Pre-release/
283--
284{-# INLINE transform #-}
285transform :: (IsStream t, Monad m) => Pipe m a b -> t m a -> t m b
286transform pipe xs = fromStreamD $ D.transform pipe (toStreamD xs)
288------------------------------------------------------------------------------
289-- Transformation Folds
290------------------------------------------------------------------------------
292-- | Right fold to a streaming monad.
293--
294-- > foldrS Stream.cons Stream.nil === id
295--
296-- 'foldrS' can be used to perform stateless stream to stream transformations
297-- like map and filter in general. It can be coupled with a scan to perform
298-- stateful transformations. However, note that the custom map and filter
299-- routines can be much more efficient than this due to better stream fusion.
300--
301-- >>> Stream.toList $ Stream.foldrS Stream.cons Stream.nil $ Stream.fromList [1..5]
302-- [1,2,3,4,5]
303--
304-- Find if any element in the stream is 'True':
305--
306-- >>> 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)
307-- [True]
308--
309-- Map (+2) on odd elements and filter out the even elements:
310--
311-- >>> 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)
312-- [3,5,7]
313--
314-- 'foldrM' can also be represented in terms of 'foldrS', however, the former
315-- is much more efficient:
316--
317-- > foldrM f z s = runIdentityT $ foldrS (\x xs -> lift $ f x (runIdentityT xs)) (lift z) s
318--
319-- /Pre-release/
320{-# INLINE foldrS #-}
321foldrS :: IsStream t => (a -> t m b -> t m b) -> t m b -> t m a -> t m b
322foldrS = K.foldrS
324-- | Right fold to a transformer monad. This is the most general right fold
325-- function. 'foldrS' is a special case of 'foldrT', however 'foldrS'
326-- implementation can be more efficient:
327--
328-- > foldrS = foldrT
329-- > foldrM f z s = runIdentityT $ foldrT (\x xs -> lift $ f x (runIdentityT xs)) (lift z) s
330--
331-- 'foldrT' can be used to translate streamly streams to other transformer
332-- monads e.g. to a different streaming type.
333--
334-- /Pre-release/
335{-# INLINE foldrT #-}
336foldrT :: (IsStream t, Monad m, Monad (s m), MonadTrans s)
337 => (a -> s m b -> s m b) -> s m b -> t m a -> s m b
338foldrT f z s = S.foldrT f z (toStreamS s)
340------------------------------------------------------------------------------
341-- Transformation by Mapping
342------------------------------------------------------------------------------
344-- |
345-- @
346-- mapM f = sequence . map f
347-- @
348--
349-- Apply a monadic function to each element of the stream and replace it with
350-- the output of the resulting action.
351--
352-- @
353-- >>> drain $ Stream.mapM putStr $ Stream.fromList ["a", "b", "c"]
354-- abc
355--
356-- >>> :{
357-- drain $ Stream.replicateM 10 (return 1)
358-- & (fromSerial . Stream.mapM (\x -> threadDelay 1000000 >> print x))
359-- :}
360-- 1
361-- ...
362-- 1
363--
364-- > drain $ Stream.replicateM 10 (return 1)
365-- & (fromAsync . Stream.mapM (\x -> threadDelay 1000000 >> print x))
366-- @
367--
368-- /Concurrent (do not use with 'fromParallel' on infinite streams)/
369--
370-- @since 0.1.0
371{-# INLINE_EARLY mapM #-}
372mapM :: (IsStream t, MonadAsync m) => (a -> m b) -> t m a -> t m b
373mapM = K.mapM
375{-# RULES "mapM serial" mapM = mapMSerial #-}
376{-# INLINE mapMSerial #-}
377mapMSerial :: Monad m => (a -> m b) -> SerialT m a -> SerialT m b
378mapMSerial = Serial.mapM
380-- |
381-- @
382-- sequence = mapM id
383-- @
384--
385-- Replace the elements of a stream of monadic actions with the outputs of
386-- those actions.
387--
388-- @
389-- >>> drain $ Stream.sequence $ Stream.fromList [putStr "a", putStr "b", putStrLn "c"]
390-- abc
391--
392-- >>> :{
393-- drain $ Stream.replicateM 10 (return $ threadDelay 1000000 >> print 1)
394-- & (fromSerial . Stream.sequence)
395-- :}
396-- 1
397-- ...
398-- 1
399--
400-- >>> :{
401-- drain $ Stream.replicateM 10 (return $ threadDelay 1000000 >> print 1)
402-- & (fromAsync . Stream.sequence)
403-- :}
404-- 1
405-- ...
406-- 1
407--
408-- @
409--
410-- /Concurrent (do not use with 'fromParallel' on infinite streams)/
411--
412-- @since 0.1.0
413{-# INLINE sequence #-}
414sequence :: (IsStream t, MonadAsync m) => t m (m a) -> t m a
415sequence m = fromStreamS $ S.sequence (toStreamS m)
417------------------------------------------------------------------------------
418-- Mapping side effects
419------------------------------------------------------------------------------
421-- | Tap the data flowing through a stream into a 'Fold'. For example, you may
422-- add a tap to log the contents flowing through the stream. The fold is used
423-- only for effects, its result is discarded.
424--
425-- @
426-- Fold m a b
427-- |
428-- -----stream m a ---------------stream m a-----
429--
430-- @
431--
432-- >>> Stream.drain $ Stream.tap (Fold.drainBy print) (Stream.enumerateFromTo 1 2)
433-- 1
434-- 2
435--
436-- Compare with 'trace'.
437--
438-- @since 0.7.0
439{-# INLINE tap #-}
440tap :: (IsStream t, Monad m) => FL.Fold m a b -> t m a -> t m a
441tap f xs = D.fromStreamD $ D.tap f (D.toStreamD xs)
443-- XXX Remove this. It can be expressed in terms of Fold.sampleFromThen.
444--
445-- | @tapOffsetEvery offset n@ taps every @n@th element in the stream
446-- starting at @offset@. @offset@ can be between @0@ and @n - 1@. Offset 0
447-- means start at the first element in the stream. If the offset is outside
448-- this range then @offset `mod` n@ is used as offset.
449--
450-- >>> Stream.drain $ Stream.tapOffsetEvery 0 2 (Fold.rmapM print Fold.toList) $ Stream.enumerateFromTo 0 10
451-- [0,2,4,6,8,10]
453--
454-- /Pre-release/
455--
456{-# INLINE tapOffsetEvery #-}
457tapOffsetEvery :: (IsStream t, Monad m)
458 => Int -> Int -> FL.Fold m a b -> t m a -> t m a
459tapOffsetEvery offset n f xs =
460 D.fromStreamD $ D.tapOffsetEvery offset n f (D.toStreamD xs)
462-- | Redirect a copy of the stream to a supplied fold and run it concurrently
463-- in an independent thread. The fold may buffer some elements. The buffer size
464-- is determined by the prevailing 'maxBuffer' setting.
465--
466-- @
467-- Stream m a -> m b
468-- |
469-- -----stream m a ---------------stream m a-----
470--
471-- @
472--
473-- @
474-- >>> Stream.drain $ Stream.tapAsync (Fold.drainBy print) (Stream.enumerateFromTo 1 2)
475-- 1
476-- 2
477--
478-- @
479--
480-- Exceptions from the concurrently running fold are propagated to the current
481-- computation. Note that, because of buffering in the fold, exceptions may be
482-- delayed and may not correspond to the current element being processed in the
483-- parent stream, but we guarantee that before the parent stream stops the tap
484-- finishes and all exceptions from it are drained.
485--
486--
487-- Compare with 'tap'.
488--
489-- /Pre-release/
490{-# INLINE tapAsync #-}
491tapAsync :: (IsStream t, MonadAsync m) => FL.Fold m a b -> t m a -> t m a
492tapAsync f xs = D.fromStreamD $ Par.tapAsyncF f (D.toStreamD xs)
494-- | @pollCounts predicate transform fold stream@ counts those elements in the
495-- stream that pass the @predicate@. The resulting count stream is sent to
496-- another thread which transforms it using @transform@ and then folds it using
497-- @fold@. The thread is automatically cleaned up if the stream stops or
498-- aborts due to exception.
499--
500-- For example, to print the count of elements processed every second:
501--
502-- @
503-- > Stream.drain $ Stream.pollCounts (const True) (Stream.rollingMap (-) . Stream.delayPost 1) (FLold.drainBy print)
504-- $ Stream.enumerateFrom 0
505-- @
506--
507-- Note: This may not work correctly on 32-bit machines.
508--
509-- /Pre-release/
510--
511{-# INLINE pollCounts #-}
512pollCounts ::
513 (IsStream t, MonadAsync m)
514 => (a -> Bool)
515 -> (t m Int -> t m Int)
516 -> Fold m Int b
517 -> t m a
518 -> t m a
519pollCounts predicate transf f xs =
520 D.fromStreamD
521 $ D.pollCounts predicate (D.toStreamD . transf . D.fromStreamD) f
522 $ D.toStreamD xs
524-- | Calls the supplied function with the number of elements consumed
525-- every @n@ seconds. The given function is run in a separate thread
526-- until the end of the stream. In case there is an exception in the
527-- stream the thread is killed during the next major GC.
528--
529-- Note: The action is not guaranteed to run if the main thread exits.
530--
531-- @
532-- > delay n = threadDelay (round $ n * 1000000) >> return n
533-- > Stream.toList $ Stream.tapRate 2 (\n -> print $ show n ++ " elements processed") (delay 1 Stream.|: delay 0.5 Stream.|: delay 0.5 Stream.|: Stream.nil)
534-- "2 elements processed"
535-- [1.0,0.5,0.5]
536-- "1 elements processed"
537-- @
538--
539-- Note: This may not work correctly on 32-bit machines.
540--
541-- /Pre-release/
542{-# INLINE tapRate #-}
543tapRate ::
544 (IsStream t, MonadAsync m, MonadCatch m)
545 => Double
546 -> (Int -> m b)
547 -> t m a
548 -> t m a
549tapRate n f xs = D.fromStreamD $ D.tapRate n f $ D.toStreamD xs
551-- | Apply a monadic function to each element flowing through the stream and
552-- discard the results.
553--
554-- @
555-- >>> Stream.drain $ Stream.trace print (Stream.enumerateFromTo 1 2)
556-- 1
557-- 2
558--
559-- @
560--
561-- Compare with 'tap'.
562--
563-- @since 0.7.0
564{-# INLINE trace #-}
565trace :: (IsStream t, MonadAsync m) => (a -> m b) -> t m a -> t m a
566trace f = mapM (\x -> void (f x) >> return x)
568-- | Perform a side effect before yielding each element of the stream and
569-- discard the results.
570--
571-- @
572-- >>> Stream.drain $ Stream.trace_ (print "got here") (Stream.enumerateFromTo 1 2)
573-- "got here"
574-- "got here"
575--
576-- @
577--
578-- Same as 'interspersePrefix_' but always serial.
579--
580-- See also: 'trace'
581--
582-- /Pre-release/
583{-# INLINE trace_ #-}
584trace_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
585trace_ eff = Serial.mapM (\x -> eff >> return x)
587------------------------------------------------------------------------------
588-- Scanning with a Fold
589------------------------------------------------------------------------------
591-- | Scan a stream using the given monadic fold.
592--
593-- >>> Stream.toList $ Stream.takeWhile (< 10) $ Stream.scan Fold.sum (Stream.fromList [1..10])
594-- [0,1,3,6]
595--
596-- @since 0.7.0
597{-# INLINE scan #-}
598scan :: (IsStream t, Monad m) => Fold m a b -> t m a -> t m b
599scan = P.scanOnce
601-- | Postscan a stream using the given monadic fold.
602--
603-- The following example extracts the input stream up to a point where the
604-- running average of elements is no more than 10:
605--
606-- >>> import Data.Maybe (fromJust)
607-- >>> let avg = Fold.teeWith (/) Fold.sum (fmap fromIntegral Fold.length)
608-- >>> :{
609-- Stream.toList
610-- $ Stream.map (fromJust . fst)
611-- $ Stream.takeWhile (\(_,x) -> x <= 10)
612-- $ Stream.postscan (Fold.tee Fold.last avg) (Stream.enumerateFromTo 1.0 100.0)
613-- :}
614-- [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]
615--
616-- @since 0.7.0
617{-# INLINE postscan #-}
618postscan :: (IsStream t, Monad m) => Fold m a b -> t m a -> t m b
619postscan = P.postscanOnce
621------------------------------------------------------------------------------
622-- Scanning - Transformation by Folding
623------------------------------------------------------------------------------
625-- XXX It may be useful to have a version of scan where we can keep the
626-- accumulator independent of the value emitted. So that we do not necessarily
627-- have to keep a value in the accumulator which we are not using. We can pass
628-- an extraction function that will take the accumulator and the current value
629-- of the element and emit the next value in the stream. That will also make it
630-- possible to modify the accumulator after using it. In fact, the step function
631-- can return new accumulator and the value to be emitted. The signature would
632-- be more like mapAccumL. Or we can change the signature of scanx to
633-- accommodate this.
634--
635-- | Strict left scan with an extraction function. Like 'scanl'', but applies a
636-- user supplied extraction function (the third argument) at each step. This is
637-- designed to work with the @foldl@ library. The suffix @x@ is a mnemonic for
638-- extraction.
639--
640-- /Since 0.2.0/
641--
642-- /Since: 0.7.0 (Monad m constraint)/
643{-# DEPRECATED scanx "Please use scanl followed by map instead." #-}
644{-# INLINE scanx #-}
645scanx :: (IsStream t, Monad m) => (x -> a -> x) -> x -> (x -> b) -> t m a -> t m b
646scanx = P.scanlx'
648-- XXX this needs to be concurrent
649-- XXX because of the use of D.cons for appending, scanlM' has quadratic
650-- complexity when iterated over a stream. We should use StreamK style scanlM'
651-- for linear performance on iteration.
652--
653-- | Like 'scanl'' but with a monadic step function and a monadic seed.
654--
655-- /Since: 0.4.0/
656--
657-- /Since: 0.8.0 (signature change)/
658{-# INLINE scanlM' #-}
659scanlM' :: (IsStream t, Monad m) => (b -> a -> m b) -> m b -> t m a -> t m b
660scanlM' step begin m = fromStreamD $ D.scanlM' step begin $ toStreamD m
662-- XXX because of the use of D.cons for appending, scanl' has quadratic
663-- complexity when iterated over a stream. We should use StreamK style scanlM'
664-- for linear performance on iteration.
666-- | Strict left scan. Like 'map', 'scanl'' too is a one to one transformation,
667-- however it adds an extra element.
668--
669-- @
670-- >>> Stream.toList $ Stream.scanl' (+) 0 $ fromList [1,2,3,4]
671-- [0,1,3,6,10]
672--
673-- @
674--
675-- @
676-- >>> Stream.toList $ Stream.scanl' (flip (:)) [] $ Stream.fromList [1,2,3,4]
677-- [[],[1],[2,1],[3,2,1],[4,3,2,1]]
678--
679-- @
680--
681-- The output of 'scanl'' is the initial value of the accumulator followed by
682-- all the intermediate steps and the final result of 'foldl''.
683--
684-- By streaming the accumulated state after each fold step, we can share the
685-- state across multiple stages of stream composition. Each stage can modify or
686-- extend the state, do some processing with it and emit it for the next stage,
687-- thus modularizing the stream processing. This can be useful in
688-- stateful or event-driven programming.
689--
690-- Consider the following monolithic example, computing the sum and the product
691-- of the elements in a stream in one go using a @foldl'@:
692--
693-- @
694-- >>> Stream.foldl' (\(s, p) x -> (s + x, p * x)) (0,1) $ Stream.fromList [1,2,3,4]
695-- (10,24)
696--
697-- @
698--
699-- Using @scanl'@ we can make it modular by computing the sum in the first
700-- stage and passing it down to the next stage for computing the product:
701--
702-- @
703-- >>> :{
704-- Stream.foldl' (\(_, p) (s, x) -> (s, p * x)) (0,1)
705-- $ Stream.scanl' (\(s, _) x -> (s + x, x)) (0,1)
706-- $ Stream.fromList [1,2,3,4]
707-- :}
708-- (10,24)
709--
710-- @
711--
712-- IMPORTANT: 'scanl'' evaluates the accumulator to WHNF. To avoid building
713-- lazy expressions inside the accumulator, it is recommended that a strict
714-- data structure is used for accumulator.
715--
716-- >>> scanl' f z xs = scanlM' (\a b -> return (f a b)) (return z) xs
717-- >>> scanl' f z xs = z `Stream.cons` postscanl' f z xs
718--
719-- See also: 'usingStateT'
720--
721-- @since 0.2.0
722{-# INLINE scanl' #-}
723scanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
724scanl' step z m = fromStreamS $ S.scanl' step z $ toStreamS m
726-- | Like 'scanl'' but does not stream the initial value of the accumulator.
727--
728-- >>> postscanl' f z = postscanlM' (\a b -> return (f a b)) (return z)
729-- >>> postscanl' f z xs = Stream.drop 1 $ Stream.scanl' f z xs
730--
731-- @since 0.7.0
732{-# INLINE postscanl' #-}
733postscanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
734postscanl' step z m = fromStreamD $ D.postscanl' step z $ toStreamD m
736-- XXX prescanl does not sound very useful, enable only if there is a
737-- compelling use case.
738--
739-- | Like scanl' but does not stream the final value of the accumulator.
740--
741-- /Pre-release/
742{-# INLINE prescanl' #-}
743prescanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
744prescanl' step z m = fromStreamD $ D.prescanl' step z $ toStreamD m
746-- XXX this needs to be concurrent
747-- | Like prescanl' but with a monadic step function and a monadic seed.
748--
749-- /Pre-release/
750{-# INLINE prescanlM' #-}
751prescanlM' :: (IsStream t, Monad m) => (b -> a -> m b) -> m b -> t m a -> t m b
752prescanlM' step z m = fromStreamD $ D.prescanlM' step z $ toStreamD m
754-- XXX this needs to be concurrent
755-- | Like 'scanl1'' but with a monadic step function.
756--
757-- @since 0.6.0
758{-# INLINE scanl1M' #-}
759scanl1M' :: (IsStream t, Monad m) => (a -> a -> m a) -> t m a -> t m a
760scanl1M' step m = fromStreamD $ D.scanl1M' step $ toStreamD m
762-- | Like 'scanl'' but for a non-empty stream. The first element of the stream
763-- is used as the initial value of the accumulator. Does nothing if the stream
764-- is empty.
765--
766-- @
767-- >>> Stream.toList $ Stream.scanl1' (+) $ fromList [1,2,3,4]
768-- [1,3,6,10]
769--
770-- @
771--
772-- @since 0.6.0
773{-# INLINE scanl1' #-}
774scanl1' :: (IsStream t, Monad m) => (a -> a -> a) -> t m a -> t m a
775scanl1' step m = fromStreamD $ D.scanl1' step $ toStreamD m
777------------------------------------------------------------------------------
778-- Filtering
779------------------------------------------------------------------------------
781-- | Modify a @t m a -> t m a@ stream transformation that accepts a predicate
782-- @(a -> b)@ to accept @((s, a) -> b)@ instead, provided a transformation @t m
783-- a -> t m (s, a)@. Convenient to filter with index or time.
784--
785-- @
786-- filterWithIndex = with indexed filter
787-- filterWithAbsTime = with timestamped filter
788-- filterWithRelTime = with timeIndexed filter
789-- @
790--
791-- /Pre-release/
792{-# INLINE with #-}
793with :: forall (t :: (Type -> Type) -> Type -> Type) m a b s. Functor (t m) =>
794 (t m a -> t m (s, a))
795 -> (((s, a) -> b) -> t m (s, a) -> t m (s, a))
796 -> (((s, a) -> b) -> t m a -> t m a)
797with f comb g = fmap snd . comb g . f
799-- | Include only those elements that pass a predicate.
800--
801-- @since 0.1.0
802{-# INLINE filter #-}
803#if __GLASGOW_HASKELL__ != 802
804-- GHC 8.2.2 crashes with this code, when used with "stack"
805filter :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m a
806filter p m = fromStreamS $ S.filter p $ toStreamS m
807#else
808filter :: IsStream t => (a -> Bool) -> t m a -> t m a
809filter = K.filter
810#endif
812-- | Same as 'filter' but with a monadic predicate.
813--
814-- @since 0.4.0
815{-# INLINE filterM #-}
816filterM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
817filterM p m = fromStreamD $ D.filterM p $ toStreamD m
819-- | Drop repeated elements that are adjacent to each other using the supplied
820-- comparison function.
821--
822-- @uniq = uniqBy (==)
823--
824-- To strip duplicate path separators:
825--
826-- @
827-- f x y = x == '/' && x == y
828-- Stream.toList $ Stream.uniqBy f $ Stream.fromList "//a//b"
829-- "/a/b"
830-- @
831--
832-- Space: @O(1)@
833--
834-- See also: 'nubBy'.
835--
836-- /Pre-release/
837--
838{-# INLINE uniqBy #-}
839uniqBy :: (IsStream t, Monad m, Functor (t m)) =>
840 (a -> a -> Bool) -> t m a -> t m a
841uniqBy eq =
842 catMaybes . rollingMap (\x y -> if x `eq` y then Nothing else Just y)
844-- | Drop repeated elements that are adjacent to each other.
845--
846-- @since 0.6.0
847{-# INLINE uniq #-}
848uniq :: (Eq a, IsStream t, Monad m) => t m a -> t m a
849uniq = fromStreamD . D.uniq . toStreamD
851-- | Strip all leading and trailing occurrences of an element passing a
852-- predicate and make all other consecutive occurrences uniq.
853--
854-- @
855-- prune p = dropWhileAround p $ uniqBy (x y -> p x && p y)
856-- @
857--
858-- @
859-- > Stream.prune isSpace (Stream.fromList " hello world! ")
860-- "hello world!"
861--
862-- @
863--
864-- Space: @O(1)@
865--
866-- /Unimplemented/
867{-# INLINE prune #-}
868prune ::
869 -- (IsStream t, Monad m, Eq a) =>
870 (a -> Bool) -> t m a -> t m a
871prune = error "Not implemented yet!"
873-- Possible implementation:
874-- @repeated =
875-- Stream.catMaybes . Stream.parseMany (Parser.groupBy (==) Fold.repeated)@
876--
877-- 'Fold.repeated' should return 'Just' when repeated, and 'Nothing' for a
878-- single element.
879--
880-- | Emit only repeated elements, once.
881--
882-- /Unimplemented/
883repeated :: -- (IsStream t, Monad m, Eq a) =>
884 t m a -> t m a
885repeated = undefined
887-- We can have more efficient implementations for nubOrd and nubInt by using
888-- Set and IntSet to find/remove duplication. For Hashable we can use a
889-- hashmap. Use rewrite rules to specialize to more efficient impls.
890--
891-- | Drop repeated elements anywhere in the stream.
892--
893-- /Caution: not scalable for infinite streams/
894--
895-- /See also: nubWindowBy/
896--
897-- /Unimplemented/
898--
899{-# INLINE nubBy #-}
900nubBy :: -- (IsStream t, Monad m) =>
901 (a -> a -> Bool) -> t m a -> t m a
902nubBy = undefined -- fromStreamD . D.nubBy . toStreamD
904-- | Drop repeated elements within the specified tumbling window in the stream.
905--
906-- @nubBy = nubWindowBy maxBound@
907--
908-- /Unimplemented/
909--
910{-# INLINE nubWindowBy #-}
911nubWindowBy :: -- (IsStream t, Monad m) =>
912 Int -> (a -> a -> Bool) -> t m a -> t m a
913nubWindowBy = undefined -- fromStreamD . D.nubWithinBy . toStreamD
915-- | Deletes the first occurrence of the element in the stream that satisfies
916-- the given equality predicate.
917--
918-- @
919-- >>> Stream.toList $ Stream.deleteBy (==) 3 $ Stream.fromList [1,3,3,5]
920-- [1,3,5]
921--
922-- @
923--
924-- @since 0.6.0
925{-# INLINE deleteBy #-}
926deleteBy :: (IsStream t, Monad m) => (a -> a -> Bool) -> a -> t m a -> t m a
927deleteBy cmp x m = fromStreamS $ S.deleteBy cmp x (toStreamS m)
929------------------------------------------------------------------------------
930-- Lossy Buffering
931------------------------------------------------------------------------------
933-- XXX We could use 'maxBuffer Block/Drop/Rotate/Sample' instead. However we
934-- may want to have the evaluation rate independent of the sampling rate. To
935-- support that we can decouple evaluation and sampling in independent stages.
936-- The sampling stage would strictly evaluate and sample, the evaluation stage
937-- would control the evaluation rate.
939-- | Evaluate the input stream continuously and keep only the oldest @n@
940-- elements in the buffer, discard the new ones when the buffer is full. When
941-- the output stream is evaluated it consumes the values from the buffer in a
942-- FIFO manner.
943--
944-- /Unimplemented/
945--
946{-# INLINE sampleOld #-}
947sampleOld :: -- (IsStream t, Monad m) =>
948 Int -> t m a -> t m a
949sampleOld = undefined
951-- | Evaluate the input stream continuously and keep only the latest @n@
952-- elements in a ring buffer, keep discarding the older ones to make space for
953-- the new ones. When the output stream is evaluated it consumes the values
954-- from the buffer in a FIFO manner.
955--
956-- /Unimplemented/
957--
958{-# INLINE sampleNew #-}
959sampleNew :: -- (IsStream t, Monad m) =>
960 Int -> t m a -> t m a
961sampleNew = undefined
963-- | Like 'sampleNew' but samples at uniform intervals to match the consumer
964-- rate. Note that 'sampleNew' leads to non-uniform sampling depending on the
965-- consumer pattern.
966--
967-- /Unimplemented/
968--
969{-# INLINE sampleRate #-}
970sampleRate :: -- (IsStream t, Monad m) =>
971 Double -> t m a -> t m a
972sampleRate = undefined
974------------------------------------------------------------------------------
975-- Trimming
976------------------------------------------------------------------------------
978-- | Same as 'takeWhile' but with a monadic predicate.
979--
980-- @since 0.4.0
981{-# INLINE takeWhileM #-}
982takeWhileM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
983takeWhileM p m = fromStreamD $ D.takeWhileM p $ toStreamD m
985-- See the lastN fold for impl hints. Use a Data.Array based ring buffer.
986--
987-- takeLast n = Stream.concatM . fmap Array.toStream . fold Fold.lastN
988--
989-- | Take @n@ elements at the end of the stream.
990--
991-- O(n) space, where n is the number elements taken.
992--
993-- /Unimplemented/
994{-# INLINE takeLast #-}
995takeLast :: -- (IsStream t, Monad m) =>
996 Int -> t m a -> t m a
997takeLast = undefined -- fromStreamD $ D.takeLast n $ toStreamD m
999-- | Take time interval @i@ seconds at the end of the stream.
1001-- O(n) space, where n is the number elements taken.
1003-- /Unimplemented/
1004{-# INLINE takeLastInterval #-}
1005takeLastInterval :: -- (IsStream t, Monad m) =>
1006 Double -> t m a -> t m a
1007takeLastInterval = undefined -- fromStreamD $ D.takeLast n $ toStreamD m
1009-- | Take all consecutive elements at the end of the stream for which the
1010-- predicate is true.
1012-- O(n) space, where n is the number elements taken.
1014-- /Unimplemented/
1015{-# INLINE takeWhileLast #-}
1016takeWhileLast :: -- (IsStream t, Monad m) =>
1017 (a -> Bool) -> t m a -> t m a
1018takeWhileLast = undefined -- fromStreamD $ D.takeWhileLast n $ toStreamD m
1020-- | Like 'takeWhile' and 'takeWhileLast' combined.
1022-- O(n) space, where n is the number elements taken from the end.
1024-- /Unimplemented/
1025{-# INLINE takeWhileAround #-}
1026takeWhileAround :: -- (IsStream t, Monad m) =>
1027 (a -> Bool) -> t m a -> t m a
1028takeWhileAround = undefined -- fromStreamD $ D.takeWhileAround n $ toStreamD m
1030-- | @takeInterval duration@ yields stream elements upto specified time
1031-- @duration@. The duration starts when the stream is evaluated for the first
1032-- time, before the first element is yielded. The time duration is checked
1033-- before generating each element, if the duration has expired the stream
1034-- stops.
1036-- The total time taken in executing the stream is guaranteed to be /at least/
1037-- @duration@, however, because the duration is checked before generating an
1038-- element, the upper bound is indeterminate and depends on the time taken in
1039-- generating and processing the last element.
1041-- No element is yielded if the duration is zero. At least one element is
1042-- yielded if the duration is non-zero.
1044-- /Pre-release/
1046{-# INLINE takeInterval #-}
1047takeInterval ::(MonadIO m, IsStream t, TimeUnit64 d) => d -> t m a -> t m a
1048takeInterval d = fromStreamD . D.takeByTime d . toStreamD
1050-- | Drop elements in the stream as long as the predicate succeeds and then
1051-- take the rest of the stream.
1053-- @since 0.1.0
1054{-# INLINE dropWhile #-}
1055dropWhile :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m a
1056dropWhile p m = fromStreamS $ S.dropWhile p $ toStreamS m
1058-- | Same as 'dropWhile' but with a monadic predicate.
1060-- @since 0.4.0
1061{-# INLINE dropWhileM #-}
1062dropWhileM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
1063dropWhileM p m = fromStreamD $ D.dropWhileM p $ toStreamD m
1065-- | @dropInterval duration@ drops stream elements until specified @duration@ has
1066-- passed. The duration begins when the stream is evaluated for the first
1067-- time. The time duration is checked /after/ generating a stream element, the
1068-- element is yielded if the duration has expired otherwise it is dropped.
1070-- The time elapsed before starting to generate the first element is /at most/
1071-- @duration@, however, because the duration expiry is checked after the
1072-- element is generated, the lower bound is indeterminate and depends on the
1073-- time taken in generating an element.
1075-- All elements are yielded if the duration is zero.
1077-- /Pre-release/
1079{-# INLINE dropInterval #-}
1080dropInterval ::(MonadIO m, IsStream t, TimeUnit64 d) => d -> t m a -> t m a
1081dropInterval d = fromStreamD . D.dropByTime d . toStreamD
1083-- | Drop @n@ elements at the end of the stream.
1085-- O(n) space, where n is the number elements dropped.
1087-- /Unimplemented/
1088{-# INLINE dropLast #-}
1089dropLast :: -- (IsStream t, Monad m) =>
1090 Int -> t m a -> t m a
1091dropLast = undefined -- fromStreamD $ D.dropLast n $ toStreamD m
1093-- | Drop time interval @i@ seconds at the end of the stream.
1095-- O(n) space, where n is the number elements dropped.
1097-- /Unimplemented/
1098{-# INLINE dropLastInterval #-}
1099dropLastInterval :: -- (IsStream t, Monad m) =>
1100 Int -> t m a -> t m a
1101dropLastInterval = undefined
1103-- | Drop all consecutive elements at the end of the stream for which the
1104-- predicate is true.
1106-- O(n) space, where n is the number elements dropped.
1108-- /Unimplemented/
1109{-# INLINE dropWhileLast #-}
1110dropWhileLast :: -- (IsStream t, Monad m) =>
1111 (a -> Bool) -> t m a -> t m a
1112dropWhileLast = undefined -- fromStreamD $ D.dropWhileLast n $ toStreamD m
1114-- | Like 'dropWhile' and 'dropWhileLast' combined.
1116-- O(n) space, where n is the number elements dropped from the end.
1118-- /Unimplemented/
1119{-# INLINE dropWhileAround #-}
1120dropWhileAround :: -- (IsStream t, Monad m) =>
1121 (a -> Bool) -> t m a -> t m a
1122dropWhileAround = undefined -- fromStreamD $ D.dropWhileAround n $ toStreamD m
1124------------------------------------------------------------------------------
1125-- Inserting Elements
1126------------------------------------------------------------------------------
1128-- | @insertBy cmp elem stream@ inserts @elem@ before the first element in
1129-- @stream@ that is less than @elem@ when compared using @cmp@.
1131-- @
1132-- insertBy cmp x = 'mergeBy' cmp ('fromPure' x)
1133-- @
1135-- @
1136-- >>> Stream.toList $ Stream.insertBy compare 2 $ Stream.fromList [1,3,5]
1137-- [1,2,3,5]
1139-- @
1141-- @since 0.6.0
1142{-# INLINE insertBy #-}
1143insertBy ::
1144 (IsStream t, Monad m) => (a -> a -> Ordering) -> a -> t m a -> t m a
1145insertBy cmp x m = fromStreamS $ S.insertBy cmp x (toStreamS m)
1147-- | Insert a pure value between successive elements of a stream.
1149-- >>> Stream.toList $ Stream.intersperse ',' $ Stream.fromList "hello"
1150-- "h,e,l,l,o"
1152-- @since 0.7.0
1153{-# INLINE intersperse #-}
1154intersperse :: (IsStream t, MonadAsync m) => a -> t m a -> t m a
1155intersperse a = fromStreamS . S.intersperse a . toStreamS
1157-- | Insert a side effect before consuming an element of a stream except the
1158-- first one.
1160-- >>> Stream.drain $ Stream.trace putChar $ Stream.intersperseM_ (putChar '.') $ Stream.fromList "hello"
1161-- h.e.l.l.o
1163-- /Pre-release/
1164{-# INLINE intersperseM_ #-}
1165intersperseM_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
1166intersperseM_ m = fromStreamD . D.intersperseM_ m . toStreamD
1168-- | Intersperse a monadic action into the input stream after every @n@
1169-- elements.
1171-- @
1172-- > Stream.toList $ Stream.intersperseBySpan 2 (return ',') $ Stream.fromList "hello"
1173-- "he,ll,o"
1175-- @
1177-- /Unimplemented/
1178{-# INLINE intersperseBySpan #-}
1179intersperseBySpan :: -- IsStream t =>
1180 Int -> m a -> t m a -> t m a
1181intersperseBySpan _n _f _xs = undefined
1183-- | Insert an effect and its output after consuming an element of a stream.
1185-- >>> Stream.toList $ Stream.trace putChar $ intersperseSuffix (putChar '.' >> return ',') $ Stream.fromList "hello"
1186-- h.,e.,l.,l.,o.,"h,e,l,l,o,"
1188-- /Pre-release/
1189{-# INLINE intersperseSuffix #-}
1190intersperseSuffix :: (IsStream t, Monad m) => m a -> t m a -> t m a
1191intersperseSuffix m = fromStreamD . D.intersperseSuffix m . toStreamD
1193-- | Insert a side effect after consuming an element of a stream.
1195-- @
1196-- >>> Stream.mapM_ putChar $ Stream.intersperseSuffix_ (threadDelay 1000000) $ Stream.fromList "hello"
1197-- hello
1199-- @
1201-- /Pre-release/
1203{-# INLINE intersperseSuffix_ #-}
1204intersperseSuffix_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
1205intersperseSuffix_ m = fromStreamD . D.intersperseSuffix_ m . toStreamD
1207-- XXX Use an offset argument, like tapOffsetEvery
1209-- | Like 'intersperseSuffix' but intersperses an effectful action into the
1210-- input stream after every @n@ elements and after the last element.
1212-- >>> Stream.toList $ Stream.intersperseSuffixBySpan 2 (return ',') $ Stream.fromList "hello"
1213-- "he,ll,o,"
1215-- /Pre-release/
1217{-# INLINE intersperseSuffixBySpan #-}
1218intersperseSuffixBySpan :: (IsStream t, Monad m)
1219 => Int -> m a -> t m a -> t m a
1220intersperseSuffixBySpan n eff =
1221 fromStreamD . D.intersperseSuffixBySpan n eff . toStreamD
1223-- | Insert a side effect before consuming an element of a stream.
1225-- >>> Stream.toList $ Stream.trace putChar $ Stream.interspersePrefix_ (putChar '.' >> return ',') $ Stream.fromList "hello"
1226-- .h.e.l.l.o"hello"
1228-- Same as 'trace_' but may be concurrent.
1230-- /Concurrent/
1232-- /Pre-release/
1234{-# INLINE interspersePrefix_ #-}
1235interspersePrefix_ :: (IsStream t, MonadAsync m) => m b -> t m a -> t m a
1236interspersePrefix_ m = mapM (\x -> void m >> return x)
1238------------------------------------------------------------------------------
1239-- Inserting Time
1240------------------------------------------------------------------------------
1242-- Note: delay must be serial.
1244-- | Introduce a delay of specified seconds before consuming an element of the
1245-- stream except the first one.
1247-- >>> Stream.mapM_ print $ Stream.timestamped $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
1248-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),1)
1249-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),2)
1250-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),3)
1252-- @since 0.8.0
1254{-# INLINE delay #-}
1255delay :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
1256delay n = intersperseM_ $ liftIO $ threadDelay $ round $ n * 1000000
1258-- Note: delay must be serial.
1260-- | Introduce a delay of specified seconds after consuming an element of a
1261-- stream.
1263-- >>> Stream.mapM_ print $ Stream.timestamped $ Stream.delayPost 1 $ Stream.enumerateFromTo 1 3
1264-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),1)
1265-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),2)
1266-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),3)
1268-- /Pre-release/
1270{-# INLINE delayPost #-}
1271delayPost :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
1272delayPost n = intersperseSuffix_ $ liftIO $ threadDelay $ round $ n * 1000000
1274-- Note: delay must be serial, that's why 'trace_' is used.
1276-- | Introduce a delay of specified seconds before consuming an element of a
1277-- stream.
1279-- >>> Stream.mapM_ print $ Stream.timestamped $ Stream.delayPre 1 $ Stream.enumerateFromTo 1 3
1280-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),1)
1281-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),2)
1282-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),3)
1284-- /Pre-release/
1286{-# INLINE delayPre #-}
1287delayPre :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
1288delayPre n = trace_ $ liftIO $ threadDelay $ round $ n * 1000000
1290------------------------------------------------------------------------------
1291-- Reorder in sequence
1292------------------------------------------------------------------------------
1294-- | Buffer until the next element in sequence arrives. The function argument
1295-- determines the difference in sequence numbers. This could be useful in
1296-- implementing sequenced streams, for example, TCP reassembly.
1298-- /Unimplemented/
1300{-# INLINE reassembleBy #-}
1301reassembleBy
1302 :: -- (IsStream t, Monad m) =>
1303 Fold m a b
1304 -> (a -> a -> Int)
1305 -> t m a
1306 -> t m b
1307reassembleBy = undefined
1309------------------------------------------------------------------------------
1310-- Position Indexing
1311------------------------------------------------------------------------------
1313-- |
1314-- > indexed = Stream.postscanl' (\(i, _) x -> (i + 1, x)) (-1,undefined)
1315-- > indexed = Stream.zipWith (,) (Stream.enumerateFrom 0)
1317-- Pair each element in a stream with its index, starting from index 0.
1319-- >>> Stream.toList $ Stream.indexed $ Stream.fromList "hello"
1320-- [(0,'h'),(1,'e'),(2,'l'),(3,'l'),(4,'o')]
1322-- @since 0.6.0
1323{-# INLINE indexed #-}
1324indexed :: (IsStream t, Monad m) => t m a -> t m (Int, a)
1325indexed = fromStreamD . D.indexed . toStreamD
1327-- |
1328-- > indexedR n = Stream.postscanl' (\(i, _) x -> (i - 1, x)) (n + 1,undefined)
1329-- > indexedR n = Stream.zipWith (,) (Stream.enumerateFromThen n (n - 1))
1331-- Pair each element in a stream with its index, starting from the
1332-- given index @n@ and counting down.
1334-- >>> Stream.toList $ Stream.indexedR 10 $ Stream.fromList "hello"
1335-- [(10,'h'),(9,'e'),(8,'l'),(7,'l'),(6,'o')]
1337-- @since 0.6.0
1338{-# INLINE indexedR #-}
1339indexedR :: (IsStream t, Monad m) => Int -> t m a -> t m (Int, a)
1340indexedR n = fromStreamD . D.indexedR n . toStreamD
1342-------------------------------------------------------------------------------
1343-- Time Indexing
1344-------------------------------------------------------------------------------
1346-- Note: The timestamp stream must be the second stream in the zip so that the
1347-- timestamp is generated after generating the stream element and not before.
1348-- If we do not do that then the following example will generate the same
1349-- timestamp for first two elements:
1351-- Stream.mapM_ print $ Stream.timestamped $ Stream.delay $ Stream.enumerateFromTo 1 3
1353-- | Pair each element in a stream with an absolute timestamp, using a clock of
1354-- specified granularity. The timestamp is generated just before the element
1355-- is consumed.
1357-- >>> Stream.mapM_ print $ Stream.timestampWith 0.01 $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
1358-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),1)
1359-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),2)
1360-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),3)
1362-- /Pre-release/
1364{-# INLINE timestampWith #-}
1365timestampWith :: (IsStream t, MonadAsync m, Functor (t m))
1366 => Double -> t m a -> t m (AbsTime, a)
1367timestampWith g stream = Z.zipWith (flip (,)) stream (absTimesWith g)
1369-- TBD: check performance vs a custom implementation without using zipWith.
1371-- /Pre-release/
1373{-# INLINE timestamped #-}
1374timestamped :: (IsStream t, MonadAsync m, Functor (t m))
1375 => t m a -> t m (AbsTime, a)
1376timestamped = timestampWith 0.01
1378-- | Pair each element in a stream with relative times starting from 0, using a
1379-- clock with the specified granularity. The time is measured just before the
1380-- element is consumed.
1382-- >>> Stream.mapM_ print $ Stream.timeIndexWith 0.01 $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
1383-- (RelTime64 (NanoSecond64 ...),1)
1384-- (RelTime64 (NanoSecond64 ...),2)
1385-- (RelTime64 (NanoSecond64 ...),3)
1387-- /Pre-release/
1389{-# INLINE timeIndexWith #-}
1390timeIndexWith :: (IsStream t, MonadAsync m, Functor (t m))
1391 => Double -> t m a -> t m (RelTime64, a)
1392timeIndexWith g stream = Z.zipWith (flip (,)) stream (relTimesWith g)
1394-- | Pair each element in a stream with relative times starting from 0, using a
1395-- 10 ms granularity clock. The time is measured just before the element is
1396-- consumed.
1398-- >>> Stream.mapM_ print $ Stream.timeIndexed $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
1399-- (RelTime64 (NanoSecond64 ...),1)
1400-- (RelTime64 (NanoSecond64 ...),2)
1401-- (RelTime64 (NanoSecond64 ...),3)
1403-- /Pre-release/
1405{-# INLINE timeIndexed #-}
1406timeIndexed :: (IsStream t, MonadAsync m, Functor (t m))
1407 => t m a -> t m (RelTime64, a)
1408timeIndexed = timeIndexWith 0.01
1410------------------------------------------------------------------------------
1411-- Searching
1412------------------------------------------------------------------------------
1414-- | Find all the indices where the value of the element in the stream is equal
1415-- to the given value.
1417-- > elemIndices a = findIndices (== a)
1419-- @since 0.5.0
1420{-# INLINE elemIndices #-}
1421elemIndices :: (IsStream t, Eq a, Monad m) => a -> t m a -> t m Int
1422elemIndices a = findIndices (== a)
1424------------------------------------------------------------------------------
1425-- Rolling map
1426------------------------------------------------------------------------------
1428-- XXX this is not a one-to-one map so calling it map may not be right.
1429-- We can perhaps call it zipWithTail or rollWith.
1431-- | Apply a function on every two successive elements of a stream. If the
1432-- stream consists of a single element the output is an empty stream.
1434-- This is the stream equivalent of the list idiom @zipWith f xs (tail xs)@.
1436-- /Pre-release/
1438{-# INLINE rollingMap #-}
1439rollingMap :: (IsStream t, Monad m) => (a -> a -> b) -> t m a -> t m b
1440rollingMap f m = fromStreamD $ D.rollingMap f $ toStreamD m
1442-- | Like 'rollingMap' but with an effectful map function.
1444-- /Pre-release/
1446{-# INLINE rollingMapM #-}
1447rollingMapM :: (IsStream t, Monad m) => (a -> a -> m b) -> t m a -> t m b
1448rollingMapM f m = fromStreamD $ D.rollingMapM f $ toStreamD m
1450------------------------------------------------------------------------------
1451-- Maybe Streams
1452------------------------------------------------------------------------------
1454-- | Map a 'Maybe' returning function to a stream, filter out the 'Nothing'
1455-- elements, and return a stream of values extracted from 'Just'.
1457-- Equivalent to:
1459-- @
1460-- mapMaybe f = Stream.map 'fromJust' . Stream.filter 'isJust' . Stream.map f
1461-- @
1463-- @since 0.3.0
1464{-# INLINE mapMaybe #-}
1465mapMaybe :: (IsStream t, Monad m) => (a -> Maybe b) -> t m a -> t m b
1466mapMaybe f m = fromStreamS $ S.mapMaybe f $ toStreamS m
1468-- | Like 'mapMaybe' but maps a monadic function.
1470-- Equivalent to:
1472-- @
1473-- mapMaybeM f = Stream.map 'fromJust' . Stream.filter 'isJust' . Stream.mapM f
1474-- @
1476-- /Concurrent (do not use with 'fromParallel' on infinite streams)/
1478-- @since 0.3.0
1479{-# INLINE_EARLY mapMaybeM #-}
1480mapMaybeM :: (IsStream t, MonadAsync m, Functor (t m))
1481 => (a -> m (Maybe b)) -> t m a -> t m b
1482mapMaybeM f = fmap fromJust . filter isJust . K.mapM f
1484{-# RULES "mapMaybeM serial" mapMaybeM = mapMaybeMSerial #-}
1485{-# INLINE mapMaybeMSerial #-}
1486mapMaybeMSerial :: Monad m => (a -> m (Maybe b)) -> SerialT m a -> SerialT m b
1487mapMaybeMSerial f m = fromStreamD $ D.mapMaybeM f $ toStreamD m
1489-- | In a stream of 'Maybe's, discard 'Nothing's and unwrap 'Just's.
1491-- /Pre-release/
1493{-# INLINE catMaybes #-}
1494catMaybes :: (IsStream t, Monad m, Functor (t m)) => t m (Maybe a) -> t m a
1495catMaybes = fmap fromJust . filter isJust
1497------------------------------------------------------------------------------
1498-- Either streams
1499------------------------------------------------------------------------------
1501-- | Discard 'Right's and unwrap 'Left's in an 'Either' stream.
1503-- /Pre-release/
1505{-# INLINE lefts #-}
1506lefts :: (IsStream t, Monad m, Functor (t m)) => t m (Either a b) -> t m a
1507lefts = fmap (fromLeft undefined) . filter isLeft
1509-- | Discard 'Left's and unwrap 'Right's in an 'Either' stream.
1511-- /Pre-release/
1513{-# INLINE rights #-}
1514rights :: (IsStream t, Monad m, Functor (t m)) => t m (Either a b) -> t m b
1515rights = fmap (fromRight undefined) . filter isRight
1517-- | Remove the either wrapper and flatten both lefts and as well as rights in
1518-- the output stream.
1520-- /Pre-release/
1522{-# INLINE both #-}
1523both :: Functor (t m) => t m (Either a a) -> t m a
1524both = fmap (either id id)
1526------------------------------------------------------------------------------
1527-- Concurrent Application
1528------------------------------------------------------------------------------
1530-- | Parallel transform application operator; applies a stream transformation
1531-- function @t m a -> t m b@ to a stream @t m a@ concurrently; the input stream
1532-- is evaluated asynchronously in an independent thread yielding elements to a
1533-- buffer and the transformation function runs in another thread consuming the
1534-- input from the buffer. '|$' is just like regular function application
1535-- operator '$' except that it is concurrent.
1537-- If you read the signature as @(t m a -> t m b) -> (t m a -> t m b)@ you can
1538-- look at it as a transformation that converts a transform function to a
1539-- buffered concurrent transform function.
1541-- The following code prints a value every second even though each stage adds a
1542-- 1 second delay.
1545-- >>> :{
1546-- Stream.drain $
1547-- Stream.mapM (\x -> threadDelay 1000000 >> print x)
1548-- |$ Stream.replicateM 3 (threadDelay 1000000 >> return 1)
1549-- :}
1550-- 1
1551-- 1
1552-- 1
1554-- /Concurrent/
1556-- /Since: 0.3.0 ("Streamly")/
1558-- @since 0.8.0
1559{-# INLINE (|$) #-}
1560(|$) :: (IsStream t, MonadAsync m) => (t m a -> t m b) -> (t m a -> t m b)
1561-- (|$) f = f . Async.mkAsync
1562(|$) f = f . Par.mkParallel
1564infixr 0 |$
1566-- | Same as '|$'.
1568-- /Internal/
1570{-# INLINE applyAsync #-}
1571applyAsync :: (IsStream t, MonadAsync m)
1572 => (t m a -> t m b) -> (t m a -> t m b)
1573applyAsync = (|$)
1575-- | Same as '|$' but with arguments reversed.
1577-- (|&) = flip (|$)
1579-- /Concurrent/
1581-- /Since: 0.3.0 ("Streamly")/
1583-- @since 0.8.0
1584{-# INLINE (|&) #-}
1585(|&) :: (IsStream t, MonadAsync m) => t m a -> (t m a -> t m b) -> t m b
1586x |& f = f |$ x
1588infixl 1 |&