on d4e6ca6 help sign in
1671 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
160 -- * Maybe Streams
161 -- Move these to Streamly.Data.Maybe.Stream?
162 , catMaybes -- XXX justs (like lefts/rights)
163 , mapMaybe
164 , mapMaybeM
166 -- * Either Streams
167 -- Move these to Streamly.Data.Either.Stream?
168 , lefts
169 , rights
170 , both
172 -- * Concurrent Evaluation
173 -- ** Concurrent Pipelines
174 -- | Run streaming stages concurrently.
176 , mkAsync
177 , mkParallel
178 , applyAsync
179 , (|$)
180 , (|&)
182 -- ** Concurrency Control
183 , maxThreads
185 -- ** Buffering and Sampling
186 -- | Evaluate strictly using a buffer of results. When the buffer becomes
187 -- full we can block, drop the new elements, drop the oldest element and
188 -- insert the new at the end or keep dropping elements uniformly to match
189 -- the rate of the consumer.
190 , maxBuffer
191 , sampleOld
192 , sampleNew
193 , sampleRate
195 -- ** Rate Limiting
196 -- | Evaluate the stream at uniform intervals to maintain a specified
197 -- evaluation rate.
198 , Rate (..)
199 , rate
200 , avgRate
201 , minRate
202 , maxRate
203 , constRate
205 -- * Diagnostics
206 , inspectMode
208 -- * Deprecated
209 , scanx
210 )
211where
213#include "inline.hs"
215import Control.Concurrent (threadDelay)
216import Control.Monad (void)
217import Control.Monad.Catch (MonadCatch)
218import Control.Monad.IO.Class (MonadIO(..))
219import Control.Monad.Trans.Class (MonadTrans(..))
220import Data.Either (isLeft, isRight)
221import Data.Kind (Type)
222import Data.Maybe (isJust, fromJust)
223import Streamly.Internal.BaseCompat (fromLeft, fromRight)
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
259#if __GLASGOW_HASKELL__ == 802
260import qualified Streamly.Internal.Data.Stream.StreamK as K
261#endif
262import qualified Streamly.Internal.Data.Stream.StreamK.Type as K
263#ifdef USE_STREAMK_ONLY
264import qualified Streamly.Internal.Data.Stream.StreamK as S
265#else
266import qualified Streamly.Internal.Data.Stream.StreamD as S
267#endif
268import qualified Prelude
270import Prelude hiding
271 ( filter, drop, dropWhile, take, takeWhile, foldr, map, mapM, sequence
272 , reverse, foldr1 , scanl, scanl1, zipWith)
274--
275-- $setup
276-- >>> :m
277-- >>> import Control.Concurrent (threadDelay)
278-- >>> import Data.Function ((&))
279-- >>> import Streamly.Prelude ((|$))
280-- >>> import Prelude hiding ( filter, drop, dropWhile, take, takeWhile, foldr, map, mapM, sequence, reverse, foldr1 , scanl, scanl1)
281-- >>> import qualified Streamly.Prelude as Stream
282-- >>> import Streamly.Internal.Data.Stream.IsStream as Stream
283-- >>> import qualified Streamly.Data.Fold as Fold
284-- >>> import qualified Streamly.Internal.Data.Fold as Fold
285-- >>> import System.IO (stdout, hSetBuffering, BufferMode(LineBuffering))
286--
287-- >>> hSetBuffering stdout LineBuffering
289------------------------------------------------------------------------------
290-- Piping
291------------------------------------------------------------------------------
293-- | Use a 'Pipe' to transform a stream.
294--
295-- /Pre-release/
296--
297{-# INLINE transform #-}
298transform :: (IsStream t, Monad m) => Pipe m a b -> t m a -> t m b
299transform pipe xs = fromStreamD $ D.transform pipe (toStreamD xs)
301------------------------------------------------------------------------------
302-- Transformation Folds
303------------------------------------------------------------------------------
305-- | Right fold to a streaming monad.
306--
307-- > foldrS Stream.cons Stream.nil === id
308--
309-- 'foldrS' can be used to perform stateless stream to stream transformations
310-- like map and filter in general. It can be coupled with a scan to perform
311-- stateful transformations. However, note that the custom map and filter
312-- routines can be much more efficient than this due to better stream fusion.
313--
314-- >>> Stream.toList $ Stream.foldrS Stream.cons Stream.nil $ Stream.fromList [1..5]
315-- [1,2,3,4,5]
316--
317-- Find if any element in the stream is 'True':
318--
319-- >>> 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)
320-- [True]
321--
322-- Map (+2) on odd elements and filter out the even elements:
323--
324-- >>> 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)
325-- [3,5,7]
326--
327-- 'foldrM' can also be represented in terms of 'foldrS', however, the former
328-- is much more efficient:
329--
330-- > foldrM f z s = runIdentityT $ foldrS (\x xs -> lift $ f x (runIdentityT xs)) (lift z) s
331--
332-- /Pre-release/
333{-# INLINE foldrS #-}
334foldrS :: IsStream t => (a -> t m b -> t m b) -> t m b -> t m a -> t m b
335foldrS f z xs =
336 fromStream
337 $ K.foldrS
338 (\y ys -> toStream $ f y (fromStream ys))
339 (toStream z)
340 (toStream xs)
342{-# INLINE foldrSShared #-}
343foldrSShared :: IsStream t => (a -> t m b -> t m b) -> t m b -> t m a -> t m b
344foldrSShared f z xs =
345 fromStream
346 $ K.foldrSShared
347 (\y ys -> toStream $ f y (fromStream ys))
348 (toStream z)
349 (toStream xs)
351-- | Right fold to a transformer monad. This is the most general right fold
352-- function. 'foldrS' is a special case of 'foldrT', however 'foldrS'
353-- implementation can be more efficient:
354--
355-- > foldrS = foldrT
356-- > foldrM f z s = runIdentityT $ foldrT (\x xs -> lift $ f x (runIdentityT xs)) (lift z) s
357--
358-- 'foldrT' can be used to translate streamly streams to other transformer
359-- monads e.g. to a different streaming type.
360--
361-- /Pre-release/
362{-# INLINE foldrT #-}
363foldrT :: (IsStream t, Monad m, Monad (s m), MonadTrans s)
364 => (a -> s m b -> s m b) -> s m b -> t m a -> s m b
365foldrT f z s = S.foldrT f z (toStreamS s)
367------------------------------------------------------------------------------
368-- Transformation by Mapping
369------------------------------------------------------------------------------
371-- |
372-- @
373-- mapM f = sequence . map f
374-- @
375--
376-- Apply a monadic function to each element of the stream and replace it with
377-- the output of the resulting action.
378--
379-- @
380-- >>> drain $ Stream.mapM putStr $ Stream.fromList ["a", "b", "c"]
381-- abc
382--
383-- >>> :{
384-- drain $ Stream.replicateM 10 (return 1)
385-- & (fromSerial . Stream.mapM (\x -> threadDelay 1000000 >> print x))
386-- :}
387-- 1
388-- ...
389-- 1
390--
391-- > drain $ Stream.replicateM 10 (return 1)
392-- & (fromAsync . Stream.mapM (\x -> threadDelay 1000000 >> print x))
393-- @
394--
395-- /Concurrent (do not use with 'fromParallel' on infinite streams)/
396--
397-- @since 0.1.0
398{-# INLINE_EARLY mapM #-}
399mapM :: forall t m a b. (IsStream t, MonadAsync m) =>
400 (a -> m b) -> t m a -> t m b
401mapM f = fromStream . K.mapMWith (toConsK (consM @t)) f . toStream
403{-# RULES "mapM serial" mapM = mapMSerial #-}
404{-# INLINE mapMSerial #-}
405mapMSerial :: Monad m => (a -> m b) -> SerialT m a -> SerialT m b
406mapMSerial = Serial.mapM
408-- |
409-- @
410-- sequence = mapM id
411-- @
412--
413-- Replace the elements of a stream of monadic actions with the outputs of
414-- those actions.
415--
416-- @
417-- >>> drain $ Stream.sequence $ Stream.fromList [putStr "a", putStr "b", putStrLn "c"]
418-- abc
419--
420-- >>> :{
421-- drain $ Stream.replicateM 3 (return $ threadDelay 1000000 >> print 1)
422-- & (fromSerial . Stream.sequence)
423-- :}
424-- 1
425-- 1
426-- 1
427--
428-- >>> :{
429-- drain $ Stream.replicateM 3 (return $ threadDelay 1000000 >> print 1)
430-- & (fromAsync . Stream.sequence)
431-- :}
432-- 1
433-- 1
434-- 1
435--
436-- @
437--
438-- /Concurrent (do not use with 'fromParallel' on infinite streams)/
439--
440-- @since 0.1.0
441{-# INLINE sequence #-}
442sequence :: (IsStream t, MonadAsync m) => t m (m a) -> t m a
443sequence = mapM id
445------------------------------------------------------------------------------
446-- Mapping side effects
447------------------------------------------------------------------------------
449-- | Tap the data flowing through a stream into a 'Fold'. For example, you may
450-- add a tap to log the contents flowing through the stream. The fold is used
451-- only for effects, its result is discarded.
452--
453-- @
454-- Fold m a b
455-- |
456-- -----stream m a ---------------stream m a-----
457--
458-- @
459--
460-- >>> Stream.drain $ Stream.tap (Fold.drainBy print) (Stream.enumerateFromTo 1 2)
461-- 1
462-- 2
463--
464-- Compare with 'trace'.
465--
466-- @since 0.7.0
467{-# INLINE tap #-}
468tap :: (IsStream t, Monad m) => FL.Fold m a b -> t m a -> t m a
469tap f xs = fromStreamD $ D.tap f (toStreamD xs)
471-- XXX Remove this. It can be expressed in terms of Fold.sampleFromThen.
472--
473-- | @tapOffsetEvery offset n@ taps every @n@th element in the stream
474-- starting at @offset@. @offset@ can be between @0@ and @n - 1@. Offset 0
475-- means start at the first element in the stream. If the offset is outside
476-- this range then @offset `mod` n@ is used as offset.
477--
478-- >>> Stream.drain $ Stream.tapOffsetEvery 0 2 (Fold.rmapM print Fold.toList) $ Stream.enumerateFromTo 0 10
479-- [0,2,4,6,8,10]
481--
482-- /Pre-release/
483--
484{-# INLINE tapOffsetEvery #-}
485tapOffsetEvery :: (IsStream t, Monad m)
486 => Int -> Int -> FL.Fold m a b -> t m a -> t m a
487tapOffsetEvery offset n f xs =
488 fromStreamD $ D.tapOffsetEvery offset n f (toStreamD xs)
490-- | Redirect a copy of the stream to a supplied fold and run it concurrently
491-- in an independent thread. The fold may buffer some elements. The buffer size
492-- is determined by the prevailing 'maxBuffer' setting.
493--
494-- @
495-- Stream m a -> m b
496-- |
497-- -----stream m a ---------------stream m a-----
498--
499-- @
500--
501-- @
502-- >>> Stream.drain $ Stream.tapAsync (Fold.drainBy print) (Stream.enumerateFromTo 1 2)
503-- 1
504-- 2
505--
506-- @
507--
508-- Exceptions from the concurrently running fold are propagated to the current
509-- computation. Note that, because of buffering in the fold, exceptions may be
510-- delayed and may not correspond to the current element being processed in the
511-- parent stream, but we guarantee that before the parent stream stops the tap
512-- finishes and all exceptions from it are drained.
513--
514--
515-- Compare with 'tap'.
516--
517-- /Pre-release/
518{-# INLINE tapAsync #-}
519tapAsync :: (IsStream t, MonadAsync m) => FL.Fold m a b -> t m a -> t m a
520tapAsync f xs = fromStreamD $ Par.tapAsyncF f (toStreamD xs)
522-- | Redirect a copy of the stream to a supplied fold and run it concurrently
523-- in an independent thread. The fold may buffer some elements. The buffer size
524-- is determined by the prevailing 'Streamly.Prelude.maxBuffer' setting.
525--
526-- @
527-- Stream m a -> m b
528-- |
529-- -----stream m a ---------------stream m a-----
530--
531-- @
532--
533-- @
534-- > S.drain $ S.tapAsync (S.mapM_ print) (S.enumerateFromTo 1 2)
535-- 1
536-- 2
537-- @
538--
539-- Exceptions from the concurrently running fold are propagated to the current
540-- computation. Note that, because of buffering in the fold, exceptions may be
541-- delayed and may not correspond to the current element being processed in the
542-- parent stream, but we guarantee that before the parent stream stops the tap
543-- finishes and all exceptions from it are drained.
544--
545--
546-- Compare with 'tap'.
547--
548-- /Pre-release/
549{-# INLINE tapAsyncK #-}
550tapAsyncK :: (IsStream t, MonadAsync m) => (t m a -> m b) -> t m a -> t m a
551tapAsyncK f m = fromStream $ Par.tapAsyncK (f . fromStream) (toStream m)
553-- | Concurrently distribute a stream to a collection of fold functions,
554-- discarding the outputs of the folds.
555--
556-- @
557-- > Stream.drain $ Stream.distributeAsync_ [Stream.mapM_ print, Stream.mapM_ print] (Stream.enumerateFromTo 1 2)
558-- 1
559-- 2
560-- 1
561-- 2
562--
563-- @
564--
565-- @
566-- distributeAsync_ = flip (foldr tapAsync)
567-- @
568--
569-- /Pre-release/
570--
571{-# INLINE distributeAsync_ #-}
572distributeAsync_ :: (Foldable f, IsStream t, MonadAsync m)
573 => f (t m a -> m b) -> t m a -> t m a
574distributeAsync_ = flip (Prelude.foldr tapAsyncK)
576-- | @pollCounts predicate transform fold stream@ counts those elements in the
577-- stream that pass the @predicate@. The resulting count stream is sent to
578-- another thread which transforms it using @transform@ and then folds it using
579-- @fold@. The thread is automatically cleaned up if the stream stops or
580-- aborts due to exception.
581--
582-- For example, to print the count of elements processed every second:
583--
584-- @
585-- > Stream.drain $ Stream.pollCounts (const True) (Stream.rollingMap (-) . Stream.delayPost 1) (FLold.drainBy print)
586-- $ Stream.enumerateFrom 0
587-- @
588--
589-- Note: This may not work correctly on 32-bit machines.
590--
591-- /Pre-release/
592--
593{-# INLINE pollCounts #-}
594pollCounts ::
595 (IsStream t, MonadAsync m)
596 => (a -> Bool)
597 -> (t m Int -> t m Int)
598 -> Fold m Int b
599 -> t m a
600 -> t m a
601pollCounts predicate transf f xs =
602 fromStreamD
603 $ D.pollCounts predicate (toStreamD . transf . fromStreamD) f
604 $ toStreamD xs
606-- | Calls the supplied function with the number of elements consumed
607-- every @n@ seconds. The given function is run in a separate thread
608-- until the end of the stream. In case there is an exception in the
609-- stream the thread is killed during the next major GC.
610--
611-- Note: The action is not guaranteed to run if the main thread exits.
612--
613-- @
614-- > delay n = threadDelay (round $ n * 1000000) >> return n
615-- > Stream.toList $ Stream.tapRate 2 (\n -> print $ show n ++ " elements processed") (delay 1 Stream.|: delay 0.5 Stream.|: delay 0.5 Stream.|: Stream.nil)
616-- "2 elements processed"
617-- [1.0,0.5,0.5]
618-- "1 elements processed"
619-- @
620--
621-- Note: This may not work correctly on 32-bit machines.
622--
623-- /Pre-release/
624{-# INLINE tapRate #-}
625tapRate ::
626 (IsStream t, MonadAsync m, MonadCatch m)
627 => Double
628 -> (Int -> m b)
629 -> t m a
630 -> t m a
631tapRate n f xs = fromStreamD $ D.tapRate n f $ toStreamD xs
633-- | Apply a monadic function to each element flowing through the stream and
634-- discard the results.
635--
636-- @
637-- >>> Stream.drain $ Stream.trace print (Stream.enumerateFromTo 1 2)
638-- 1
639-- 2
640--
641-- @
642--
643-- Compare with 'tap'.
644--
645-- @since 0.7.0
646{-# INLINE trace #-}
647trace :: (IsStream t, MonadAsync m) => (a -> m b) -> t m a -> t m a
648trace f = mapM (\x -> void (f x) >> return x)
650-- | Perform a side effect before yielding each element of the stream and
651-- discard the results.
652--
653-- @
654-- >>> Stream.drain $ Stream.trace_ (print "got here") (Stream.enumerateFromTo 1 2)
655-- "got here"
656-- "got here"
657--
658-- @
659--
660-- Same as 'interspersePrefix_' but always serial.
661--
662-- See also: 'trace'
663--
664-- /Pre-release/
665{-# INLINE trace_ #-}
666trace_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
667trace_ eff = fromStreamD . D.mapM (\x -> eff >> return x) . toStreamD
669------------------------------------------------------------------------------
670-- Scanning with a Fold
671------------------------------------------------------------------------------
673-- | Scan a stream using the given monadic fold.
674--
675-- >>> Stream.toList $ Stream.takeWhile (< 10) $ Stream.scan Fold.sum (Stream.fromList [1..10])
676-- [0,1,3,6]
677--
678-- @since 0.7.0
679{-# INLINE scan #-}
680scan :: (IsStream t, Monad m) => Fold m a b -> t m a -> t m b
681-- scan = P.scanOnce
682scan fld m = fromStreamD $ D.scanOnce fld $ toStreamD m
684-- | Postscan a stream using the given monadic fold.
685--
686-- The following example extracts the input stream up to a point where the
687-- running average of elements is no more than 10:
688--
689-- >>> import Data.Maybe (fromJust)
690-- >>> let avg = Fold.teeWith (/) Fold.sum (fmap fromIntegral Fold.length)
691-- >>> :{
692-- Stream.toList
693-- $ Stream.map (fromJust . fst)
694-- $ Stream.takeWhile (\(_,x) -> x <= 10)
695-- $ Stream.postscan (Fold.tee Fold.last avg) (Stream.enumerateFromTo 1.0 100.0)
696-- :}
697-- [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]
698--
699-- @since 0.7.0
700{-# INLINE postscan #-}
701postscan :: (IsStream t, Monad m) => Fold m a b -> t m a -> t m b
702postscan fld = fromStreamD . D.postscanOnce fld . toStreamD
704------------------------------------------------------------------------------
705-- Scanning - Transformation by Folding
706------------------------------------------------------------------------------
708-- XXX It may be useful to have a version of scan where we can keep the
709-- accumulator independent of the value emitted. So that we do not necessarily
710-- have to keep a value in the accumulator which we are not using. We can pass
711-- an extraction function that will take the accumulator and the current value
712-- of the element and emit the next value in the stream. That will also make it
713-- possible to modify the accumulator after using it. In fact, the step function
714-- can return new accumulator and the value to be emitted. The signature would
715-- be more like mapAccumL. Or we can change the signature of scanx to
716-- accommodate this.
717--
718-- | Strict left scan with an extraction function. Like 'scanl'', but applies a
719-- user supplied extraction function (the third argument) at each step. This is
720-- designed to work with the @foldl@ library. The suffix @x@ is a mnemonic for
721-- extraction.
722--
723-- /Since 0.2.0/
724--
725-- /Since: 0.7.0 (Monad m constraint)/
726{-# DEPRECATED scanx "Please use scanl followed by map instead." #-}
727{-# INLINE scanx #-}
728scanx :: (IsStream t, Monad m) => (x -> a -> x) -> x -> (x -> b) -> t m a -> t m b
729scanx step begin done = fromStreamS . S.scanlx' step begin done . toStreamS
731-- XXX this needs to be concurrent
732-- XXX because of the use of D.cons for appending, scanlM' has quadratic
733-- complexity when iterated over a stream. We should use StreamK style scanlM'
734-- for linear performance on iteration.
735--
736-- | Like 'scanl'' but with a monadic step function and a monadic seed.
737--
738-- /Since: 0.4.0/
739--
740-- /Since: 0.8.0 (signature change)/
741{-# INLINE scanlM' #-}
742scanlM' :: (IsStream t, Monad m) => (b -> a -> m b) -> m b -> t m a -> t m b
743scanlM' step begin m = fromStreamD $ D.scanlM' step begin $ toStreamD m
745-- XXX because of the use of D.cons for appending, scanl' has quadratic
746-- complexity when iterated over a stream. We should use StreamK style scanlM'
747-- for linear performance on iteration.
749-- | Strict left scan. Like 'map', 'scanl'' too is a one to one transformation,
750-- however it adds an extra element.
751--
752-- @
753-- >>> Stream.toList $ Stream.scanl' (+) 0 $ fromList [1,2,3,4]
754-- [0,1,3,6,10]
755--
756-- @
757--
758-- @
759-- >>> Stream.toList $ Stream.scanl' (flip (:)) [] $ Stream.fromList [1,2,3,4]
760-- [[],[1],[2,1],[3,2,1],[4,3,2,1]]
761--
762-- @
763--
764-- The output of 'scanl'' is the initial value of the accumulator followed by
765-- all the intermediate steps and the final result of 'foldl''.
766--
767-- By streaming the accumulated state after each fold step, we can share the
768-- state across multiple stages of stream composition. Each stage can modify or
769-- extend the state, do some processing with it and emit it for the next stage,
770-- thus modularizing the stream processing. This can be useful in
771-- stateful or event-driven programming.
772--
773-- Consider the following monolithic example, computing the sum and the product
774-- of the elements in a stream in one go using a @foldl'@:
775--
776-- @
777-- >>> Stream.foldl' (\(s, p) x -> (s + x, p * x)) (0,1) $ Stream.fromList [1,2,3,4]
778-- (10,24)
779--
780-- @
781--
782-- Using @scanl'@ we can make it modular by computing the sum in the first
783-- stage and passing it down to the next stage for computing the product:
784--
785-- @
786-- >>> :{
787-- Stream.foldl' (\(_, p) (s, x) -> (s, p * x)) (0,1)
788-- $ Stream.scanl' (\(s, _) x -> (s + x, x)) (0,1)
789-- $ Stream.fromList [1,2,3,4]
790-- :}
791-- (10,24)
792--
793-- @
794--
795-- IMPORTANT: 'scanl'' evaluates the accumulator to WHNF. To avoid building
796-- lazy expressions inside the accumulator, it is recommended that a strict
797-- data structure is used for accumulator.
798--
799-- >>> scanl' f z xs = scanlM' (\a b -> return (f a b)) (return z) xs
800-- >>> scanl' f z xs = z `Stream.cons` postscanl' f z xs
801--
802-- See also: 'usingStateT'
803--
804-- @since 0.2.0
805{-# INLINE scanl' #-}
806scanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
807scanl' step z m = fromStreamS $ S.scanl' step z $ toStreamS m
809-- | Like 'scanl'' but does not stream the initial value of the accumulator.
810--
811-- >>> postscanl' f z = postscanlM' (\a b -> return (f a b)) (return z)
812-- >>> postscanl' f z xs = Stream.drop 1 $ Stream.scanl' f z xs
813--
814-- @since 0.7.0
815{-# INLINE postscanl' #-}
816postscanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
817postscanl' step z m = fromStreamD $ D.postscanl' step z $ toStreamD m
819-- XXX prescanl does not sound very useful, enable only if there is a
820-- compelling use case.
821--
822-- | Like scanl' but does not stream the final value of the accumulator.
823--
824-- /Pre-release/
825{-# INLINE prescanl' #-}
826prescanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
827prescanl' step z m = fromStreamD $ D.prescanl' step z $ toStreamD m
829-- XXX this needs to be concurrent
830-- | Like prescanl' but with a monadic step function and a monadic seed.
831--
832-- /Pre-release/
833{-# INLINE prescanlM' #-}
834prescanlM' :: (IsStream t, Monad m) => (b -> a -> m b) -> m b -> t m a -> t m b
835prescanlM' step z m = fromStreamD $ D.prescanlM' step z $ toStreamD m
837-- XXX this needs to be concurrent
838-- | Like 'scanl1'' but with a monadic step function.
839--
840-- @since 0.6.0
841{-# INLINE scanl1M' #-}
842scanl1M' :: (IsStream t, Monad m) => (a -> a -> m a) -> t m a -> t m a
843scanl1M' step m = fromStreamD $ D.scanl1M' step $ toStreamD m
845-- | Like 'scanl'' but for a non-empty stream. The first element of the stream
846-- is used as the initial value of the accumulator. Does nothing if the stream
847-- is empty.
848--
849-- @
850-- >>> Stream.toList $ Stream.scanl1' (+) $ fromList [1,2,3,4]
851-- [1,3,6,10]
852--
853-- @
854--
855-- @since 0.6.0
856{-# INLINE scanl1' #-}
857scanl1' :: (IsStream t, Monad m) => (a -> a -> a) -> t m a -> t m a
858scanl1' step m = fromStreamD $ D.scanl1' step $ toStreamD m
860------------------------------------------------------------------------------
861-- Filtering
862------------------------------------------------------------------------------
864-- | Modify a @t m a -> t m a@ stream transformation that accepts a predicate
865-- @(a -> b)@ to accept @((s, a) -> b)@ instead, provided a transformation @t m
866-- a -> t m (s, a)@. Convenient to filter with index or time.
867--
868-- @
869-- filterWithIndex = with indexed filter
870-- filterWithAbsTime = with timestamped filter
871-- filterWithRelTime = with timeIndexed filter
872-- @
873--
874-- /Pre-release/
875{-# INLINE with #-}
876with :: forall (t :: (Type -> Type) -> Type -> Type) m a b s. Functor (t m) =>
877 (t m a -> t m (s, a))
878 -> (((s, a) -> b) -> t m (s, a) -> t m (s, a))
879 -> (((s, a) -> b) -> t m a -> t m a)
880with f comb g = fmap snd . comb g . f
882-- | Include only those elements that pass a predicate.
883--
884-- @since 0.1.0
885{-# INLINE filter #-}
886#if __GLASGOW_HASKELL__ != 802
887-- GHC 8.2.2 crashes with this code, when used with "stack"
888filter :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m a
889filter p m = fromStreamS $ S.filter p $ toStreamS m
890#else
891filter :: IsStream t => (a -> Bool) -> t m a -> t m a
892filter p m = fromStream $ K.filter p $ toStream m
893#endif
895-- | Same as 'filter' but with a monadic predicate.
896--
897-- @since 0.4.0
898{-# INLINE filterM #-}
899filterM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
900filterM p m = fromStreamD $ D.filterM p $ toStreamD m
902-- | Drop repeated elements that are adjacent to each other using the supplied
903-- comparison function.
904--
905-- @uniq = uniqBy (==)
906--
907-- To strip duplicate path separators:
908--
909-- @
910-- f x y = x == '/' && x == y
911-- Stream.toList $ Stream.uniqBy f $ Stream.fromList "//a//b"
912-- "/a/b"
913-- @
914--
915-- Space: @O(1)@
916--
917-- See also: 'nubBy'.
918--
919-- /Pre-release/
920--
921{-# INLINE uniqBy #-}
922uniqBy :: (IsStream t, Monad m, Functor (t m)) =>
923 (a -> a -> Bool) -> t m a -> t m a
924uniqBy eq =
925 catMaybes . rollingMap (\x y -> if x `eq` y then Nothing else Just y)
927-- | Drop repeated elements that are adjacent to each other.
928--
929-- @since 0.6.0
930{-# INLINE uniq #-}
931uniq :: (Eq a, IsStream t, Monad m) => t m a -> t m a
932uniq = fromStreamD . D.uniq . toStreamD
934-- | Strip all leading and trailing occurrences of an element passing a
935-- predicate and make all other consecutive occurrences uniq.
936--
937-- @
938-- prune p = dropWhileAround p $ uniqBy (x y -> p x && p y)
939-- @
940--
941-- @
942-- > Stream.prune isSpace (Stream.fromList " hello world! ")
943-- "hello world!"
944--
945-- @
946--
947-- Space: @O(1)@
948--
949-- /Unimplemented/
950{-# INLINE prune #-}
951prune ::
952 -- (IsStream t, Monad m, Eq a) =>
953 (a -> Bool) -> t m a -> t m a
954prune = error "Not implemented yet!"
956-- Possible implementation:
957-- @repeated =
958-- Stream.catMaybes . Stream.parseMany (Parser.groupBy (==) Fold.repeated)@
959--
960-- 'Fold.repeated' should return 'Just' when repeated, and 'Nothing' for a
961-- single element.
962--
963-- | Emit only repeated elements, once.
964--
965-- /Unimplemented/
966repeated :: -- (IsStream t, Monad m, Eq a) =>
967 t m a -> t m a
968repeated = undefined
970-- We can have more efficient implementations for nubOrd and nubInt by using
971-- Set and IntSet to find/remove duplication. For Hashable we can use a
972-- hashmap. Use rewrite rules to specialize to more efficient impls.
973--
974-- | Drop repeated elements anywhere in the stream.
975--
976-- /Caution: not scalable for infinite streams/
977--
978-- /See also: nubWindowBy/
979--
980-- /Unimplemented/
981--
982{-# INLINE nubBy #-}
983nubBy :: -- (IsStream t, Monad m) =>
984 (a -> a -> Bool) -> t m a -> t m a
985nubBy = undefined -- fromStreamD . D.nubBy . toStreamD
987-- | Drop repeated elements within the specified tumbling window in the stream.
988--
989-- @nubBy = nubWindowBy maxBound@
990--
991-- /Unimplemented/
992--
993{-# INLINE nubWindowBy #-}
994nubWindowBy :: -- (IsStream t, Monad m) =>
995 Int -> (a -> a -> Bool) -> t m a -> t m a
996nubWindowBy = undefined -- fromStreamD . D.nubWithinBy . toStreamD
998-- | Deletes the first occurrence of the element in the stream that satisfies
999-- the given equality predicate.
1001-- @
1002-- >>> Stream.toList $ Stream.deleteBy (==) 3 $ Stream.fromList [1,3,3,5]
1003-- [1,3,5]
1005-- @
1007-- @since 0.6.0
1008{-# INLINE deleteBy #-}
1009deleteBy :: (IsStream t, Monad m) => (a -> a -> Bool) -> a -> t m a -> t m a
1010deleteBy cmp x m = fromStreamS $ S.deleteBy cmp x (toStreamS m)
1012------------------------------------------------------------------------------
1013-- Lossy Buffering
1014------------------------------------------------------------------------------
1016-- XXX We could use 'maxBuffer Block/Drop/Rotate/Sample' instead. However we
1017-- may want to have the evaluation rate independent of the sampling rate. To
1018-- support that we can decouple evaluation and sampling in independent stages.
1019-- The sampling stage would strictly evaluate and sample, the evaluation stage
1020-- would control the evaluation rate.
1022-- | Evaluate the input stream continuously and keep only the oldest @n@
1023-- elements in the buffer, discard the new ones when the buffer is full. When
1024-- the output stream is evaluated it consumes the values from the buffer in a
1025-- FIFO manner.
1027-- /Unimplemented/
1029{-# INLINE sampleOld #-}
1030sampleOld :: -- (IsStream t, Monad m) =>
1031 Int -> t m a -> t m a
1032sampleOld = undefined
1034-- | Evaluate the input stream continuously and keep only the latest @n@
1035-- elements in a ring buffer, keep discarding the older ones to make space for
1036-- the new ones. When the output stream is evaluated it consumes the values
1037-- from the buffer in a FIFO manner.
1039-- /Unimplemented/
1041{-# INLINE sampleNew #-}
1042sampleNew :: -- (IsStream t, Monad m) =>
1043 Int -> t m a -> t m a
1044sampleNew = undefined
1046-- | Like 'sampleNew' but samples at uniform intervals to match the consumer
1047-- rate. Note that 'sampleNew' leads to non-uniform sampling depending on the
1048-- consumer pattern.
1050-- /Unimplemented/
1052{-# INLINE sampleRate #-}
1053sampleRate :: -- (IsStream t, Monad m) =>
1054 Double -> t m a -> t m a
1055sampleRate = undefined
1057------------------------------------------------------------------------------
1058-- Trimming
1059------------------------------------------------------------------------------
1061-- | Same as 'takeWhile' but with a monadic predicate.
1063-- @since 0.4.0
1064{-# INLINE takeWhileM #-}
1065takeWhileM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
1066takeWhileM p m = fromStreamD $ D.takeWhileM p $ toStreamD m
1068-- See the lastN fold for impl hints. Use a Data.Array based ring buffer.
1070-- takeLast n = Stream.concatM . fmap Array.toStream . fold Fold.lastN
1072-- | Take @n@ elements at the end of the stream.
1074-- O(n) space, where n is the number elements taken.
1076-- /Unimplemented/
1077{-# INLINE takeLast #-}
1078takeLast :: -- (IsStream t, Monad m) =>
1079 Int -> t m a -> t m a
1080takeLast = undefined -- fromStreamD $ D.takeLast n $ toStreamD m
1082-- | Take time interval @i@ seconds at the end of the stream.
1084-- O(n) space, where n is the number elements taken.
1086-- /Unimplemented/
1087{-# INLINE takeLastInterval #-}
1088takeLastInterval :: -- (IsStream t, Monad m) =>
1089 Double -> t m a -> t m a
1090takeLastInterval = undefined -- fromStreamD $ D.takeLast n $ toStreamD m
1092-- | Take all consecutive elements at the end of the stream for which the
1093-- predicate is true.
1095-- O(n) space, where n is the number elements taken.
1097-- /Unimplemented/
1098{-# INLINE takeWhileLast #-}
1099takeWhileLast :: -- (IsStream t, Monad m) =>
1100 (a -> Bool) -> t m a -> t m a
1101takeWhileLast = undefined -- fromStreamD $ D.takeWhileLast n $ toStreamD m
1103-- | Like 'takeWhile' and 'takeWhileLast' combined.
1105-- O(n) space, where n is the number elements taken from the end.
1107-- /Unimplemented/
1108{-# INLINE takeWhileAround #-}
1109takeWhileAround :: -- (IsStream t, Monad m) =>
1110 (a -> Bool) -> t m a -> t m a
1111takeWhileAround = undefined -- fromStreamD $ D.takeWhileAround n $ toStreamD m
1113-- | @takeInterval duration@ yields stream elements upto specified time
1114-- @duration@. The duration starts when the stream is evaluated for the first
1115-- time, before the first element is yielded. The time duration is checked
1116-- before generating each element, if the duration has expired the stream
1117-- stops.
1119-- The total time taken in executing the stream is guaranteed to be /at least/
1120-- @duration@, however, because the duration is checked before generating an
1121-- element, the upper bound is indeterminate and depends on the time taken in
1122-- generating and processing the last element.
1124-- No element is yielded if the duration is zero. At least one element is
1125-- yielded if the duration is non-zero.
1127-- /Pre-release/
1129{-# INLINE takeInterval #-}
1130takeInterval ::(MonadIO m, IsStream t, TimeUnit64 d) => d -> t m a -> t m a
1131takeInterval d = fromStreamD . D.takeByTime d . toStreamD
1133-- | Drop elements in the stream as long as the predicate succeeds and then
1134-- take the rest of the stream.
1136-- @since 0.1.0
1137{-# INLINE dropWhile #-}
1138dropWhile :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m a
1139dropWhile p m = fromStreamS $ S.dropWhile p $ toStreamS m
1141-- | Same as 'dropWhile' but with a monadic predicate.
1143-- @since 0.4.0
1144{-# INLINE dropWhileM #-}
1145dropWhileM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
1146dropWhileM p m = fromStreamD $ D.dropWhileM p $ toStreamD m
1148-- | @dropInterval duration@ drops stream elements until specified @duration@ has
1149-- passed. The duration begins when the stream is evaluated for the first
1150-- time. The time duration is checked /after/ generating a stream element, the
1151-- element is yielded if the duration has expired otherwise it is dropped.
1153-- The time elapsed before starting to generate the first element is /at most/
1154-- @duration@, however, because the duration expiry is checked after the
1155-- element is generated, the lower bound is indeterminate and depends on the
1156-- time taken in generating an element.
1158-- All elements are yielded if the duration is zero.
1160-- /Pre-release/
1162{-# INLINE dropInterval #-}
1163dropInterval ::(MonadIO m, IsStream t, TimeUnit64 d) => d -> t m a -> t m a
1164dropInterval d = fromStreamD . D.dropByTime d . toStreamD
1166-- | Drop @n@ elements at the end of the stream.
1168-- O(n) space, where n is the number elements dropped.
1170-- /Unimplemented/
1171{-# INLINE dropLast #-}
1172dropLast :: -- (IsStream t, Monad m) =>
1173 Int -> t m a -> t m a
1174dropLast = undefined -- fromStreamD $ D.dropLast n $ toStreamD m
1176-- | Drop time interval @i@ seconds at the end of the stream.
1178-- O(n) space, where n is the number elements dropped.
1180-- /Unimplemented/
1181{-# INLINE dropLastInterval #-}
1182dropLastInterval :: -- (IsStream t, Monad m) =>
1183 Int -> t m a -> t m a
1184dropLastInterval = undefined
1186-- | Drop all consecutive elements at the end of the stream for which the
1187-- predicate is true.
1189-- O(n) space, where n is the number elements dropped.
1191-- /Unimplemented/
1192{-# INLINE dropWhileLast #-}
1193dropWhileLast :: -- (IsStream t, Monad m) =>
1194 (a -> Bool) -> t m a -> t m a
1195dropWhileLast = undefined -- fromStreamD $ D.dropWhileLast n $ toStreamD m
1197-- | Like 'dropWhile' and 'dropWhileLast' combined.
1199-- O(n) space, where n is the number elements dropped from the end.
1201-- /Unimplemented/
1202{-# INLINE dropWhileAround #-}
1203dropWhileAround :: -- (IsStream t, Monad m) =>
1204 (a -> Bool) -> t m a -> t m a
1205dropWhileAround = undefined -- fromStreamD $ D.dropWhileAround n $ toStreamD m
1207------------------------------------------------------------------------------
1208-- Inserting Elements
1209------------------------------------------------------------------------------
1211-- | @insertBy cmp elem stream@ inserts @elem@ before the first element in
1212-- @stream@ that is less than @elem@ when compared using @cmp@.
1214-- @
1215-- insertBy cmp x = 'mergeBy' cmp ('fromPure' x)
1216-- @
1218-- @
1219-- >>> Stream.toList $ Stream.insertBy compare 2 $ Stream.fromList [1,3,5]
1220-- [1,2,3,5]
1222-- @
1224-- @since 0.6.0
1225{-# INLINE insertBy #-}
1226insertBy ::
1227 (IsStream t, Monad m) => (a -> a -> Ordering) -> a -> t m a -> t m a
1228insertBy cmp x m = fromStreamS $ S.insertBy cmp x (toStreamS m)
1230-- | Insert a pure value between successive elements of a stream.
1232-- >>> Stream.toList $ Stream.intersperse ',' $ Stream.fromList "hello"
1233-- "h,e,l,l,o"
1235-- @since 0.7.0
1236{-# INLINE intersperse #-}
1237intersperse :: (IsStream t, MonadAsync m) => a -> t m a -> t m a
1238intersperse a = fromStreamS . S.intersperse a . toStreamS
1240-- | Insert a side effect before consuming an element of a stream except the
1241-- first one.
1243-- >>> Stream.drain $ Stream.trace putChar $ Stream.intersperseM_ (putChar '.') $ Stream.fromList "hello"
1244-- h.e.l.l.o
1246-- /Pre-release/
1247{-# INLINE intersperseM_ #-}
1248intersperseM_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
1249intersperseM_ m = fromStreamD . D.intersperseM_ m . toStreamD
1251-- | Intersperse a monadic action into the input stream after every @n@
1252-- elements.
1254-- @
1255-- > Stream.toList $ Stream.intersperseBySpan 2 (return ',') $ Stream.fromList "hello"
1256-- "he,ll,o"
1258-- @
1260-- /Unimplemented/
1261{-# INLINE intersperseBySpan #-}
1262intersperseBySpan :: -- IsStream t =>
1263 Int -> m a -> t m a -> t m a
1264intersperseBySpan _n _f _xs = undefined
1266-- | Insert an effect and its output after consuming an element of a stream.
1268-- >>> Stream.toList $ Stream.trace putChar $ intersperseSuffix (putChar '.' >> return ',') $ Stream.fromList "hello"
1269-- h.,e.,l.,l.,o.,"h,e,l,l,o,"
1271-- /Pre-release/
1272{-# INLINE intersperseSuffix #-}
1273intersperseSuffix :: (IsStream t, Monad m) => m a -> t m a -> t m a
1274intersperseSuffix m = fromStreamD . D.intersperseSuffix m . toStreamD
1276-- | Insert a side effect after consuming an element of a stream.
1278-- @
1279-- >>> Stream.mapM_ putChar $ Stream.intersperseSuffix_ (threadDelay 1000000) $ Stream.fromList "hello"
1280-- hello
1282-- @
1284-- /Pre-release/
1286{-# INLINE intersperseSuffix_ #-}
1287intersperseSuffix_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
1288intersperseSuffix_ m = fromStreamD . D.intersperseSuffix_ m . toStreamD
1290-- XXX Use an offset argument, like tapOffsetEvery
1292-- | Like 'intersperseSuffix' but intersperses an effectful action into the
1293-- input stream after every @n@ elements and after the last element.
1295-- >>> Stream.toList $ Stream.intersperseSuffixBySpan 2 (return ',') $ Stream.fromList "hello"
1296-- "he,ll,o,"
1298-- /Pre-release/
1300{-# INLINE intersperseSuffixBySpan #-}
1301intersperseSuffixBySpan :: (IsStream t, Monad m)
1302 => Int -> m a -> t m a -> t m a
1303intersperseSuffixBySpan n eff =
1304 fromStreamD . D.intersperseSuffixBySpan n eff . toStreamD
1306-- | Insert a side effect before consuming an element of a stream.
1308-- >>> Stream.toList $ Stream.trace putChar $ Stream.interspersePrefix_ (putChar '.' >> return ',') $ Stream.fromList "hello"
1309-- .h.e.l.l.o"hello"
1311-- Same as 'trace_' but may be concurrent.
1313-- /Concurrent/
1315-- /Pre-release/
1317{-# INLINE interspersePrefix_ #-}
1318interspersePrefix_ :: (IsStream t, MonadAsync m) => m b -> t m a -> t m a
1319interspersePrefix_ m = mapM (\x -> void m >> return x)
1321------------------------------------------------------------------------------
1322-- Inserting Time
1323------------------------------------------------------------------------------
1325-- Note: delay must be serial.
1327-- | Introduce a delay of specified seconds before consuming an element of the
1328-- stream except the first one.
1330-- >>> Stream.mapM_ print $ Stream.timestamped $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
1331-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),1)
1332-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),2)
1333-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),3)
1335-- @since 0.8.0
1337{-# INLINE delay #-}
1338delay :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
1339delay n = intersperseM_ $ liftIO $ threadDelay $ round $ n * 1000000
1341-- Note: delay must be serial.
1343-- | Introduce a delay of specified seconds after consuming an element of a
1344-- stream.
1346-- >>> Stream.mapM_ print $ Stream.timestamped $ Stream.delayPost 1 $ Stream.enumerateFromTo 1 3
1347-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),1)
1348-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),2)
1349-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),3)
1351-- /Pre-release/
1353{-# INLINE delayPost #-}
1354delayPost :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
1355delayPost n = intersperseSuffix_ $ liftIO $ threadDelay $ round $ n * 1000000
1357-- Note: delay must be serial, that's why 'trace_' is used.
1359-- | Introduce a delay of specified seconds before consuming an element of a
1360-- stream.
1362-- >>> Stream.mapM_ print $ Stream.timestamped $ Stream.delayPre 1 $ Stream.enumerateFromTo 1 3
1363-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),1)
1364-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),2)
1365-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),3)
1367-- /Pre-release/
1369{-# INLINE delayPre #-}
1370delayPre :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
1371delayPre n = trace_ $ liftIO $ threadDelay $ round $ n * 1000000
1373------------------------------------------------------------------------------
1374-- Reorder in sequence
1375------------------------------------------------------------------------------
1377-- | Buffer until the next element in sequence arrives. The function argument
1378-- determines the difference in sequence numbers. This could be useful in
1379-- implementing sequenced streams, for example, TCP reassembly.
1381-- /Unimplemented/
1383{-# INLINE reassembleBy #-}
1384reassembleBy
1385 :: -- (IsStream t, Monad m) =>
1386 Fold m a b
1387 -> (a -> a -> Int)
1388 -> t m a
1389 -> t m b
1390reassembleBy = undefined
1392------------------------------------------------------------------------------
1393-- Position Indexing
1394------------------------------------------------------------------------------
1396-- |
1397-- > indexed = Stream.postscanl' (\(i, _) x -> (i + 1, x)) (-1,undefined)
1398-- > indexed = Stream.zipWith (,) (Stream.enumerateFrom 0)
1400-- Pair each element in a stream with its index, starting from index 0.
1402-- >>> Stream.toList $ Stream.indexed $ Stream.fromList "hello"
1403-- [(0,'h'),(1,'e'),(2,'l'),(3,'l'),(4,'o')]
1405-- @since 0.6.0
1406{-# INLINE indexed #-}
1407indexed :: (IsStream t, Monad m) => t m a -> t m (Int, a)
1408indexed = fromStreamD . D.indexed . toStreamD
1410-- |
1411-- > indexedR n = Stream.postscanl' (\(i, _) x -> (i - 1, x)) (n + 1,undefined)
1412-- > indexedR n = Stream.zipWith (,) (Stream.enumerateFromThen n (n - 1))
1414-- Pair each element in a stream with its index, starting from the
1415-- given index @n@ and counting down.
1417-- >>> Stream.toList $ Stream.indexedR 10 $ Stream.fromList "hello"
1418-- [(10,'h'),(9,'e'),(8,'l'),(7,'l'),(6,'o')]
1420-- @since 0.6.0
1421{-# INLINE indexedR #-}
1422indexedR :: (IsStream t, Monad m) => Int -> t m a -> t m (Int, a)
1423indexedR n = fromStreamD . D.indexedR n . toStreamD
1425-------------------------------------------------------------------------------
1426-- Time Indexing
1427-------------------------------------------------------------------------------
1429-- Note: The timestamp stream must be the second stream in the zip so that the
1430-- timestamp is generated after generating the stream element and not before.
1431-- If we do not do that then the following example will generate the same
1432-- timestamp for first two elements:
1434-- Stream.mapM_ print $ Stream.timestamped $ Stream.delay $ Stream.enumerateFromTo 1 3
1436-- | Pair each element in a stream with an absolute timestamp, using a clock of
1437-- specified granularity. The timestamp is generated just before the element
1438-- is consumed.
1440-- >>> Stream.mapM_ print $ Stream.timestampWith 0.01 $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
1441-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),1)
1442-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),2)
1443-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),3)
1445-- /Pre-release/
1447{-# INLINE timestampWith #-}
1448timestampWith :: (IsStream t, MonadAsync m, Functor (t m))
1449 => Double -> t m a -> t m (AbsTime, a)
1450timestampWith g stream = zipWith (flip (,)) stream (absTimesWith g)
1452-- TBD: check performance vs a custom implementation without using zipWith.
1454-- /Pre-release/
1456{-# INLINE timestamped #-}
1457timestamped :: (IsStream t, MonadAsync m, Functor (t m))
1458 => t m a -> t m (AbsTime, a)
1459timestamped = timestampWith 0.01
1461-- | Pair each element in a stream with relative times starting from 0, using a
1462-- clock with the specified granularity. The time is measured just before the
1463-- element is consumed.
1465-- >>> Stream.mapM_ print $ Stream.timeIndexWith 0.01 $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
1466-- (RelTime64 (NanoSecond64 ...),1)
1467-- (RelTime64 (NanoSecond64 ...),2)
1468-- (RelTime64 (NanoSecond64 ...),3)
1470-- /Pre-release/
1472{-# INLINE timeIndexWith #-}
1473timeIndexWith :: (IsStream t, MonadAsync m, Functor (t m))
1474 => Double -> t m a -> t m (RelTime64, a)
1475timeIndexWith g stream = zipWith (flip (,)) stream (relTimesWith g)
1477-- | Pair each element in a stream with relative times starting from 0, using a
1478-- 10 ms granularity clock. The time is measured just before the element is
1479-- consumed.
1481-- >>> Stream.mapM_ print $ Stream.timeIndexed $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
1482-- (RelTime64 (NanoSecond64 ...),1)
1483-- (RelTime64 (NanoSecond64 ...),2)
1484-- (RelTime64 (NanoSecond64 ...),3)
1486-- /Pre-release/
1488{-# INLINE timeIndexed #-}
1489timeIndexed :: (IsStream t, MonadAsync m, Functor (t m))
1490 => t m a -> t m (RelTime64, a)
1491timeIndexed = timeIndexWith 0.01
1493------------------------------------------------------------------------------
1494-- Searching
1495------------------------------------------------------------------------------
1497-- | Find all the indices where the value of the element in the stream is equal
1498-- to the given value.
1500-- > elemIndices a = findIndices (== a)
1502-- @since 0.5.0
1503{-# INLINE elemIndices #-}
1504elemIndices :: (IsStream t, Eq a, Monad m) => a -> t m a -> t m Int
1505elemIndices a = findIndices (== a)
1507------------------------------------------------------------------------------
1508-- Rolling map
1509------------------------------------------------------------------------------
1511-- XXX this is not a one-to-one map so calling it map may not be right.
1512-- We can perhaps call it zipWithTail or rollWith.
1514-- | Apply a function on every two successive elements of a stream. If the
1515-- stream consists of a single element the output is an empty stream.
1517-- This is the stream equivalent of the list idiom @zipWith f xs (tail xs)@.
1519-- /Pre-release/
1521{-# INLINE rollingMap #-}
1522rollingMap :: (IsStream t, Monad m) => (a -> a -> b) -> t m a -> t m b
1523rollingMap f m = fromStreamD $ D.rollingMap f $ toStreamD m
1525-- | Like 'rollingMap' but with an effectful map function.
1527-- /Pre-release/
1529{-# INLINE rollingMapM #-}
1530rollingMapM :: (IsStream t, Monad m) => (a -> a -> m b) -> t m a -> t m b
1531rollingMapM f m = fromStreamD $ D.rollingMapM f $ toStreamD m
1533------------------------------------------------------------------------------
1534-- Maybe Streams
1535------------------------------------------------------------------------------
1537-- | Map a 'Maybe' returning function to a stream, filter out the 'Nothing'
1538-- elements, and return a stream of values extracted from 'Just'.
1540-- Equivalent to:
1542-- @
1543-- mapMaybe f = Stream.map 'fromJust' . Stream.filter 'isJust' . Stream.map f
1544-- @
1546-- @since 0.3.0
1547{-# INLINE mapMaybe #-}
1548mapMaybe :: (IsStream t, Monad m) => (a -> Maybe b) -> t m a -> t m b
1549mapMaybe f m = fromStreamS $ S.mapMaybe f $ toStreamS m
1551-- | Like 'mapMaybe' but maps a monadic function.
1553-- Equivalent to:
1555-- @
1556-- mapMaybeM f = Stream.map 'fromJust' . Stream.filter 'isJust' . Stream.mapM f
1557-- @
1559-- /Concurrent (do not use with 'fromParallel' on infinite streams)/
1561-- @since 0.3.0
1562{-# INLINE_EARLY mapMaybeM #-}
1563mapMaybeM :: (IsStream t, MonadAsync m, Functor (t m))
1564 => (a -> m (Maybe b)) -> t m a -> t m b
1565mapMaybeM f = fmap fromJust . filter isJust . mapM f
1567{-# RULES "mapMaybeM serial" mapMaybeM = mapMaybeMSerial #-}
1568{-# INLINE mapMaybeMSerial #-}
1569mapMaybeMSerial :: Monad m => (a -> m (Maybe b)) -> SerialT m a -> SerialT m b
1570mapMaybeMSerial f m = fromStreamD $ D.mapMaybeM f $ toStreamD m
1572-- | In a stream of 'Maybe's, discard 'Nothing's and unwrap 'Just's.
1574-- /Pre-release/
1576{-# INLINE catMaybes #-}
1577catMaybes :: (IsStream t, Monad m, Functor (t m)) => t m (Maybe a) -> t m a
1578catMaybes = fmap fromJust . filter isJust
1580------------------------------------------------------------------------------
1581-- Either streams
1582------------------------------------------------------------------------------
1584-- | Discard 'Right's and unwrap 'Left's in an 'Either' stream.
1586-- /Pre-release/
1588{-# INLINE lefts #-}
1589lefts :: (IsStream t, Monad m, Functor (t m)) => t m (Either a b) -> t m a
1590lefts = fmap (fromLeft undefined) . filter isLeft
1592-- | Discard 'Left's and unwrap 'Right's in an 'Either' stream.
1594-- /Pre-release/
1596{-# INLINE rights #-}
1597rights :: (IsStream t, Monad m, Functor (t m)) => t m (Either a b) -> t m b
1598rights = fmap (fromRight undefined) . filter isRight
1600-- | Remove the either wrapper and flatten both lefts and as well as rights in
1601-- the output stream.
1603-- /Pre-release/
1605{-# INLINE both #-}
1606both :: Functor (t m) => t m (Either a a) -> t m a
1607both = fmap (either id id)
1609------------------------------------------------------------------------------
1610-- Concurrent Application
1611------------------------------------------------------------------------------
1613-- | Parallel transform application operator; applies a stream transformation
1614-- function @t m a -> t m b@ to a stream @t m a@ concurrently; the input stream
1615-- is evaluated asynchronously in an independent thread yielding elements to a
1616-- buffer and the transformation function runs in another thread consuming the
1617-- input from the buffer. '|$' is just like regular function application
1618-- operator '$' except that it is concurrent.
1620-- If you read the signature as @(t m a -> t m b) -> (t m a -> t m b)@ you can
1621-- look at it as a transformation that converts a transform function to a
1622-- buffered concurrent transform function.
1624-- The following code prints a value every second even though each stage adds a
1625-- 1 second delay.
1628-- >>> :{
1629-- Stream.drain $
1630-- Stream.mapM (\x -> threadDelay 1000000 >> print x)
1631-- |$ Stream.replicateM 3 (threadDelay 1000000 >> return 1)
1632-- :}
1633-- 1
1634-- 1
1635-- 1
1637-- /Concurrent/
1639-- /Since: 0.3.0 ("Streamly")/
1641-- @since 0.8.0
1642{-# INLINE (|$) #-}
1643(|$) :: (IsStream t, MonadAsync m) => (t m a -> t m b) -> (t m a -> t m b)
1644-- (|$) f = f . mkAsync
1645(|$) f = f . mkParallel
1647infixr 0 |$
1649-- | Same as '|$'.
1651-- /Internal/
1653{-# INLINE applyAsync #-}
1654applyAsync :: (IsStream t, MonadAsync m)
1655 => (t m a -> t m b) -> (t m a -> t m b)
1656applyAsync = (|$)
1658-- | Same as '|$' but with arguments reversed.
1660-- (|&) = flip (|$)
1662-- /Concurrent/
1664-- /Since: 0.3.0 ("Streamly")/
1666-- @since 0.8.0
1667{-# INLINE (|&) #-}
1668(|&) :: (IsStream t, MonadAsync m) => t m a -> (t m a -> t m b) -> t m b
1669x |& f = f |$ x
1671infixl 1 |&