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