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