on 616f034 help sign in
1689 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)
222import Data.Kind (Type)
223import Data.Maybe (isJust, fromJust)
224import Streamly.Internal.BaseCompat (fromLeft, fromRight)
225import Streamly.Internal.Data.Fold.Type (Fold (..))
226import Streamly.Internal.Data.Pipe.Type (Pipe (..))
227import Streamly.Internal.Data.Stream.IsStream.Combinators
228 ( inspectMode, maxBuffer, maxThreads, rate, avgRate, minRate
229 , maxRate, constRate)
230import Streamly.Internal.Data.Stream.IsStream.Common
231 ( absTimesWith
232 , drop
233 , findIndices
234 , map
235 , postscanlM'
236 , relTimesWith
237 , reverse
238 , reverse'
239 , scanlMAfter'
240 , smapM
241 , take
242 , takeWhile
243 , interjectSuffix
244 , intersperseM
245 , mkAsync
246 , mkParallel
247 , zipWith
248 )
249import Streamly.Internal.Control.Concurrent (MonadAsync)
250import Streamly.Internal.Data.Stream.IsStream.Type
251 (IsStream(..), fromStreamS, toStreamS, fromStreamD, toStreamD, toConsK)
252import Streamly.Internal.Data.Stream.Serial (SerialT)
253import Streamly.Internal.Data.SVar (Rate(..))
254import Streamly.Internal.Data.Time.Units (TimeUnit64, AbsTime, RelTime64)
256import qualified Streamly.Internal.Data.Fold as FL
257import qualified Streamly.Internal.Data.Stream.Parallel as Par
258import qualified Streamly.Internal.Data.Stream.Serial as Serial
259import qualified Streamly.Internal.Data.Stream.StreamD as D
260#if __GLASGOW_HASKELL__ == 802
261import qualified Streamly.Internal.Data.Stream.StreamK as K
262#endif
263import qualified Streamly.Internal.Data.Stream.StreamK.Type as K
264#ifdef USE_STREAMK_ONLY
265import qualified Streamly.Internal.Data.Stream.StreamK as S
266#else
267import qualified Streamly.Internal.Data.Stream.StreamD as S
268#endif
269import qualified Prelude
271import Prelude hiding
272 ( filter, drop, dropWhile, take, takeWhile, foldr, map, mapM, sequence
273 , reverse, foldr1 , scanl, scanl1, zipWith)
275--
276-- $setup
277-- >>> :m
278-- >>> import Control.Concurrent (threadDelay)
279-- >>> import Data.Function ((&))
280-- >>> import Streamly.Prelude ((|$))
281-- >>> import Prelude hiding ( filter, drop, dropWhile, take, takeWhile, foldr, map, mapM, sequence, reverse, foldr1 , scanl, scanl1)
282-- >>> import qualified Streamly.Prelude as Stream
283-- >>> import Streamly.Internal.Data.Stream.IsStream as Stream
284-- >>> import qualified Streamly.Data.Fold as Fold
285-- >>> import qualified Streamly.Internal.Data.Fold as Fold
286-- >>> import System.IO (stdout, hSetBuffering, BufferMode(LineBuffering))
287--
288-- >>> hSetBuffering stdout LineBuffering
290------------------------------------------------------------------------------
291-- Piping
292------------------------------------------------------------------------------
294-- | Use a 'Pipe' to transform a stream.
295--
296-- /Pre-release/
297--
298{-# INLINE transform #-}
299transform :: (IsStream t, Monad m) => Pipe m a b -> t m a -> t m b
300transform pipe xs = fromStreamD $ D.transform pipe (toStreamD xs)
302------------------------------------------------------------------------------
303-- Transformation Folds
304------------------------------------------------------------------------------
306-- | Right fold to a streaming monad.
307--
308-- > foldrS Stream.cons Stream.nil === id
309--
310-- 'foldrS' can be used to perform stateless stream to stream transformations
311-- like map and filter in general. It can be coupled with a scan to perform
312-- stateful transformations. However, note that the custom map and filter
313-- routines can be much more efficient than this due to better stream fusion.
314--
315-- >>> Stream.toList $ Stream.foldrS Stream.cons Stream.nil $ Stream.fromList [1..5]
316-- [1,2,3,4,5]
317--
318-- Find if any element in the stream is 'True':
319--
320-- >>> 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)
321-- [True]
322--
323-- Map (+2) on odd elements and filter out the even elements:
324--
325-- >>> 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)
326-- [3,5,7]
327--
328-- 'foldrM' can also be represented in terms of 'foldrS', however, the former
329-- is much more efficient:
330--
331-- > foldrM f z s = runIdentityT $ foldrS (\x xs -> lift $ f x (runIdentityT xs)) (lift z) s
332--
333-- /Pre-release/
334{-# INLINE foldrS #-}
335foldrS :: IsStream t => (a -> t m b -> t m b) -> t m b -> t m a -> t m b
336foldrS f z xs =
337 fromStream
338 $ K.foldrS
339 (\y ys -> toStream $ f y (fromStream ys))
340 (toStream z)
341 (toStream xs)
343{-# INLINE foldrSShared #-}
344foldrSShared :: IsStream t => (a -> t m b -> t m b) -> t m b -> t m a -> t m b
345foldrSShared f z xs =
346 fromStream
347 $ K.foldrSShared
348 (\y ys -> toStream $ f y (fromStream ys))
349 (toStream z)
350 (toStream xs)
352-- | Right fold to a transformer monad. This is the most general right fold
353-- function. 'foldrS' is a special case of 'foldrT', however 'foldrS'
354-- implementation can be more efficient:
355--
356-- > foldrS = foldrT
357-- > foldrM f z s = runIdentityT $ foldrT (\x xs -> lift $ f x (runIdentityT xs)) (lift z) s
358--
359-- 'foldrT' can be used to translate streamly streams to other transformer
360-- monads e.g. to a different streaming type.
361--
362-- /Pre-release/
363{-# INLINE foldrT #-}
364foldrT :: (IsStream t, Monad m, Monad (s m), MonadTrans s)
365 => (a -> s m b -> s m b) -> s m b -> t m a -> s m b
366foldrT f z s = S.foldrT f z (toStreamS s)
368------------------------------------------------------------------------------
369-- Transformation by Mapping
370------------------------------------------------------------------------------
372-- |
373-- @
374-- mapM f = sequence . map f
375-- @
376--
377-- Apply a monadic function to each element of the stream and replace it with
378-- the output of the resulting action.
379--
380-- @
381-- >>> drain $ Stream.mapM putStr $ Stream.fromList ["a", "b", "c"]
382-- abc
383--
384-- >>> :{
385-- drain $ Stream.replicateM 10 (return 1)
386-- & (fromSerial . Stream.mapM (\x -> threadDelay 1000000 >> print x))
387-- :}
388-- 1
389-- ...
390-- 1
391--
392-- > drain $ Stream.replicateM 10 (return 1)
393-- & (fromAsync . Stream.mapM (\x -> threadDelay 1000000 >> print x))
394-- @
395--
396-- /Concurrent (do not use with 'fromParallel' on infinite streams)/
397--
398-- @since 0.1.0
399{-# INLINE_EARLY mapM #-}
400mapM :: forall t m a b. (IsStream t, MonadAsync m) =>
401 (a -> m b) -> t m a -> t m b
402mapM f = fromStream . K.mapMWith (toConsK (consM @t)) f . toStream
404{-# RULES "mapM serial" mapM = mapMSerial #-}
405{-# INLINE mapMSerial #-}
406mapMSerial :: Monad m => (a -> m b) -> SerialT m a -> SerialT m b
407mapMSerial = Serial.mapM
409-- |
410-- @
411-- sequence = mapM id
412-- @
413--
414-- Replace the elements of a stream of monadic actions with the outputs of
415-- those actions.
416--
417-- @
418-- >>> drain $ Stream.sequence $ Stream.fromList [putStr "a", putStr "b", putStrLn "c"]
419-- abc
420--
421-- >>> :{
422-- drain $ Stream.replicateM 3 (return $ threadDelay 1000000 >> print 1)
423-- & (fromSerial . Stream.sequence)
424-- :}
425-- 1
426-- 1
427-- 1
428--
429-- >>> :{
430-- drain $ Stream.replicateM 3 (return $ threadDelay 1000000 >> print 1)
431-- & (fromAsync . Stream.sequence)
432-- :}
433-- 1
434-- 1
435-- 1
436--
437-- @
438--
439-- /Concurrent (do not use with 'fromParallel' on infinite streams)/
440--
441-- @since 0.1.0
442{-# INLINE sequence #-}
443sequence :: (IsStream t, MonadAsync m) => t m (m a) -> t m a
444sequence = mapM id
446------------------------------------------------------------------------------
447-- Mapping side effects
448------------------------------------------------------------------------------
450-- | Tap the data flowing through a stream into a 'Fold'. For example, you may
451-- add a tap to log the contents flowing through the stream. The fold is used
452-- only for effects, its result is discarded.
453--
454-- @
455-- Fold m a b
456-- |
457-- -----stream m a ---------------stream m a-----
458--
459-- @
460--
461-- >>> Stream.drain $ Stream.tap (Fold.drainBy print) (Stream.enumerateFromTo 1 2)
462-- 1
463-- 2
464--
465-- Compare with 'trace'.
466--
467-- @since 0.7.0
468{-# INLINE tap #-}
469tap :: (IsStream t, Monad m) => FL.Fold m a b -> t m a -> t m a
470tap f xs = fromStreamD $ D.tap f (toStreamD xs)
472-- XXX Remove this. It can be expressed in terms of Fold.sampleFromThen.
473--
474-- | @tapOffsetEvery offset n@ taps every @n@th element in the stream
475-- starting at @offset@. @offset@ can be between @0@ and @n - 1@. Offset 0
476-- means start at the first element in the stream. If the offset is outside
477-- this range then @offset `mod` n@ is used as offset.
478--
479-- >>> Stream.drain $ Stream.tapOffsetEvery 0 2 (Fold.rmapM print Fold.toList) $ Stream.enumerateFromTo 0 10
480-- [0,2,4,6,8,10]
482--
483-- /Pre-release/
484--
485{-# INLINE tapOffsetEvery #-}
486tapOffsetEvery :: (IsStream t, Monad m)
487 => Int -> Int -> FL.Fold m a b -> t m a -> t m a
488tapOffsetEvery offset n f xs =
489 fromStreamD $ D.tapOffsetEvery offset n f (toStreamD xs)
491-- | Redirect a copy of the stream to a supplied fold and run it concurrently
492-- in an independent thread. The fold may buffer some elements. The buffer size
493-- is determined by the prevailing 'maxBuffer' setting.
494--
495-- @
496-- Stream m a -> m b
497-- |
498-- -----stream m a ---------------stream m a-----
499--
500-- @
501--
502-- @
503-- >>> Stream.drain $ Stream.tapAsync (Fold.drainBy print) (Stream.enumerateFromTo 1 2)
504-- 1
505-- 2
506--
507-- @
508--
509-- Exceptions from the concurrently running fold are propagated to the current
510-- computation. Note that, because of buffering in the fold, exceptions may be
511-- delayed and may not correspond to the current element being processed in the
512-- parent stream, but we guarantee that before the parent stream stops the tap
513-- finishes and all exceptions from it are drained.
514--
515--
516-- Compare with 'tap'.
517--
518-- /Pre-release/
519{-# INLINE tapAsync #-}
520tapAsync :: (IsStream t, MonadAsync m) => FL.Fold m a b -> t m a -> t m a
521tapAsync f xs = fromStreamD $ Par.tapAsyncF f (toStreamD xs)
523-- | Redirect a copy of the stream to a supplied fold and run it concurrently
524-- in an independent thread. The fold may buffer some elements. The buffer size
525-- is determined by the prevailing 'Streamly.Prelude.maxBuffer' setting.
526--
527-- @
528-- Stream m a -> m b
529-- |
530-- -----stream m a ---------------stream m a-----
531--
532-- @
533--
534-- @
535-- > S.drain $ S.tapAsync (S.mapM_ print) (S.enumerateFromTo 1 2)
536-- 1
537-- 2
538-- @
539--
540-- Exceptions from the concurrently running fold are propagated to the current
541-- computation. Note that, because of buffering in the fold, exceptions may be
542-- delayed and may not correspond to the current element being processed in the
543-- parent stream, but we guarantee that before the parent stream stops the tap
544-- finishes and all exceptions from it are drained.
545--
546--
547-- Compare with 'tap'.
548--
549-- /Pre-release/
550{-# INLINE tapAsyncK #-}
551tapAsyncK :: (IsStream t, MonadAsync m) => (t m a -> m b) -> t m a -> t m a
552tapAsyncK f m = fromStream $ Par.tapAsyncK (f . fromStream) (toStream m)
554-- | Concurrently distribute a stream to a collection of fold functions,
555-- discarding the outputs of the folds.
556--
557-- @
558-- > Stream.drain $ Stream.distributeAsync_ [Stream.mapM_ print, Stream.mapM_ print] (Stream.enumerateFromTo 1 2)
559-- 1
560-- 2
561-- 1
562-- 2
563--
564-- @
565--
566-- @
567-- distributeAsync_ = flip (foldr tapAsync)
568-- @
569--
570-- /Pre-release/
571--
572{-# INLINE distributeAsync_ #-}
573distributeAsync_ :: (Foldable f, IsStream t, MonadAsync m)
574 => f (t m a -> m b) -> t m a -> t m a
575distributeAsync_ = flip (Prelude.foldr tapAsyncK)
577-- | @pollCounts predicate transform fold stream@ counts those elements in the
578-- stream that pass the @predicate@. The resulting count stream is sent to
579-- another thread which transforms it using @transform@ and then folds it using
580-- @fold@. The thread is automatically cleaned up if the stream stops or
581-- aborts due to exception.
582--
583-- For example, to print the count of elements processed every second:
584--
585-- @
586-- > Stream.drain $ Stream.pollCounts (const True) (Stream.rollingMap (-) . Stream.delayPost 1) (FLold.drainBy print)
587-- $ Stream.enumerateFrom 0
588-- @
589--
590-- Note: This may not work correctly on 32-bit machines.
591--
592-- /Pre-release/
593--
594{-# INLINE pollCounts #-}
595pollCounts ::
596 (IsStream t, MonadAsync m)
597 => (a -> Bool)
598 -> (t m Int -> t m Int)
599 -> Fold m Int b
600 -> t m a
601 -> t m a
602pollCounts predicate transf f xs =
603 fromStreamD
604 $ D.pollCounts predicate (toStreamD . transf . fromStreamD) f
605 $ toStreamD xs
607-- | Calls the supplied function with the number of elements consumed
608-- every @n@ seconds. The given function is run in a separate thread
609-- until the end of the stream. In case there is an exception in the
610-- stream the thread is killed during the next major GC.
611--
612-- Note: The action is not guaranteed to run if the main thread exits.
613--
614-- @
615-- > delay n = threadDelay (round $ n * 1000000) >> return n
616-- > Stream.toList $ Stream.tapRate 2 (\n -> print $ show n ++ " elements processed") (delay 1 Stream.|: delay 0.5 Stream.|: delay 0.5 Stream.|: Stream.nil)
617-- "2 elements processed"
618-- [1.0,0.5,0.5]
619-- "1 elements processed"
620-- @
621--
622-- Note: This may not work correctly on 32-bit machines.
623--
624-- /Pre-release/
625{-# INLINE tapRate #-}
626tapRate ::
627 (IsStream t, MonadAsync m, MonadCatch m)
628 => Double
629 -> (Int -> m b)
630 -> t m a
631 -> t m a
632tapRate n f xs = fromStreamD $ D.tapRate n f $ toStreamD xs
634-- | Apply a monadic function to each element flowing through the stream and
635-- discard the results.
636--
637-- @
638-- >>> Stream.drain $ Stream.trace print (Stream.enumerateFromTo 1 2)
639-- 1
640-- 2
641--
642-- @
643--
644-- Compare with 'tap'.
645--
646-- @since 0.7.0
647{-# INLINE trace #-}
648trace :: (IsStream t, MonadAsync m) => (a -> m b) -> t m a -> t m a
649trace f = mapM (\x -> void (f x) >> return x)
651-- | Perform a side effect before yielding each element of the stream and
652-- discard the results.
653--
654-- @
655-- >>> Stream.drain $ Stream.trace_ (print "got here") (Stream.enumerateFromTo 1 2)
656-- "got here"
657-- "got here"
658--
659-- @
660--
661-- Same as 'interspersePrefix_' but always serial.
662--
663-- See also: 'trace'
664--
665-- /Pre-release/
666{-# INLINE trace_ #-}
667trace_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
668trace_ eff = fromStreamD . D.mapM (\x -> eff >> return x) . toStreamD
670------------------------------------------------------------------------------
671-- Scanning with a Fold
672------------------------------------------------------------------------------
674-- | Scan a stream using the given monadic fold.
675--
676-- >>> Stream.toList $ Stream.takeWhile (< 10) $ Stream.scan Fold.sum (Stream.fromList [1..10])
677-- [0,1,3,6]
678--
679-- @since 0.7.0
680{-# INLINE scan #-}
681scan :: (IsStream t, Monad m) => Fold m a b -> t m a -> t m b
682-- scan = P.scanOnce
683scan fld m = fromStreamD $ D.scanOnce fld $ toStreamD m
685-- | Postscan a stream using the given monadic fold.
686--
687-- The following example extracts the input stream up to a point where the
688-- running average of elements is no more than 10:
689--
690-- >>> import Data.Maybe (fromJust)
691-- >>> let avg = Fold.teeWith (/) Fold.sum (fmap fromIntegral Fold.length)
692-- >>> :{
693-- Stream.toList
694-- $ Stream.map (fromJust . fst)
695-- $ Stream.takeWhile (\(_,x) -> x <= 10)
696-- $ Stream.postscan (Fold.tee Fold.last avg) (Stream.enumerateFromTo 1.0 100.0)
697-- :}
698-- [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]
699--
700-- @since 0.7.0
701{-# INLINE postscan #-}
702postscan :: (IsStream t, Monad m) => Fold m a b -> t m a -> t m b
703postscan fld = fromStreamD . D.postscanOnce fld . toStreamD
705------------------------------------------------------------------------------
706-- Scanning - Transformation by Folding
707------------------------------------------------------------------------------
709-- XXX It may be useful to have a version of scan where we can keep the
710-- accumulator independent of the value emitted. So that we do not necessarily
711-- have to keep a value in the accumulator which we are not using. We can pass
712-- an extraction function that will take the accumulator and the current value
713-- of the element and emit the next value in the stream. That will also make it
714-- possible to modify the accumulator after using it. In fact, the step function
715-- can return new accumulator and the value to be emitted. The signature would
716-- be more like mapAccumL. Or we can change the signature of scanx to
717-- accommodate this.
718--
719-- | Strict left scan with an extraction function. Like 'scanl'', but applies a
720-- user supplied extraction function (the third argument) at each step. This is
721-- designed to work with the @foldl@ library. The suffix @x@ is a mnemonic for
722-- extraction.
723--
724-- /Since 0.2.0/
725--
726-- /Since: 0.7.0 (Monad m constraint)/
727{-# DEPRECATED scanx "Please use scanl followed by map instead." #-}
728{-# INLINE scanx #-}
729scanx :: (IsStream t, Monad m) => (x -> a -> x) -> x -> (x -> b) -> t m a -> t m b
730scanx step begin done = fromStreamS . S.scanlx' step begin done . toStreamS
732-- XXX this needs to be concurrent
733-- XXX because of the use of D.cons for appending, scanlM' has quadratic
734-- complexity when iterated over a stream. We should use StreamK style scanlM'
735-- for linear performance on iteration.
736--
737-- | Like 'scanl'' but with a monadic step function and a monadic seed.
738--
739-- /Since: 0.4.0/
740--
741-- /Since: 0.8.0 (signature change)/
742{-# INLINE scanlM' #-}
743scanlM' :: (IsStream t, Monad m) => (b -> a -> m b) -> m b -> t m a -> t m b
744scanlM' step begin m = fromStreamD $ D.scanlM' step begin $ toStreamD m
746-- XXX because of the use of D.cons for appending, scanl' has quadratic
747-- complexity when iterated over a stream. We should use StreamK style scanlM'
748-- for linear performance on iteration.
750-- | Strict left scan. Like 'map', 'scanl'' too is a one to one transformation,
751-- however it adds an extra element.
752--
753-- @
754-- >>> Stream.toList $ Stream.scanl' (+) 0 $ fromList [1,2,3,4]
755-- [0,1,3,6,10]
756--
757-- @
758--
759-- @
760-- >>> Stream.toList $ Stream.scanl' (flip (:)) [] $ Stream.fromList [1,2,3,4]
761-- [[],[1],[2,1],[3,2,1],[4,3,2,1]]
762--
763-- @
764--
765-- The output of 'scanl'' is the initial value of the accumulator followed by
766-- all the intermediate steps and the final result of 'foldl''.
767--
768-- By streaming the accumulated state after each fold step, we can share the
769-- state across multiple stages of stream composition. Each stage can modify or
770-- extend the state, do some processing with it and emit it for the next stage,
771-- thus modularizing the stream processing. This can be useful in
772-- stateful or event-driven programming.
773--
774-- Consider the following monolithic example, computing the sum and the product
775-- of the elements in a stream in one go using a @foldl'@:
776--
777-- @
778-- >>> Stream.foldl' (\(s, p) x -> (s + x, p * x)) (0,1) $ Stream.fromList [1,2,3,4]
779-- (10,24)
780--
781-- @
782--
783-- Using @scanl'@ we can make it modular by computing the sum in the first
784-- stage and passing it down to the next stage for computing the product:
785--
786-- @
787-- >>> :{
788-- Stream.foldl' (\(_, p) (s, x) -> (s, p * x)) (0,1)
789-- $ Stream.scanl' (\(s, _) x -> (s + x, x)) (0,1)
790-- $ Stream.fromList [1,2,3,4]
791-- :}
792-- (10,24)
793--
794-- @
795--
796-- IMPORTANT: 'scanl'' evaluates the accumulator to WHNF. To avoid building
797-- lazy expressions inside the accumulator, it is recommended that a strict
798-- data structure is used for accumulator.
799--
800-- >>> scanl' f z xs = scanlM' (\a b -> return (f a b)) (return z) xs
801-- >>> scanl' f z xs = z `Stream.cons` postscanl' f z xs
802--
803-- See also: 'usingStateT'
804--
805-- @since 0.2.0
806{-# INLINE scanl' #-}
807scanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
808scanl' step z m = fromStreamS $ S.scanl' step z $ toStreamS m
810-- | Like 'scanl'' but does not stream the initial value of the accumulator.
811--
812-- >>> postscanl' f z = postscanlM' (\a b -> return (f a b)) (return z)
813-- >>> postscanl' f z xs = Stream.drop 1 $ Stream.scanl' f z xs
814--
815-- @since 0.7.0
816{-# INLINE postscanl' #-}
817postscanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
818postscanl' step z m = fromStreamD $ D.postscanl' step z $ toStreamD m
820-- XXX prescanl does not sound very useful, enable only if there is a
821-- compelling use case.
822--
823-- | Like scanl' but does not stream the final value of the accumulator.
824--
825-- /Pre-release/
826{-# INLINE prescanl' #-}
827prescanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
828prescanl' step z m = fromStreamD $ D.prescanl' step z $ toStreamD m
830-- XXX this needs to be concurrent
831-- | Like prescanl' but with a monadic step function and a monadic seed.
832--
833-- /Pre-release/
834{-# INLINE prescanlM' #-}
835prescanlM' :: (IsStream t, Monad m) => (b -> a -> m b) -> m b -> t m a -> t m b
836prescanlM' step z m = fromStreamD $ D.prescanlM' step z $ toStreamD m
838-- XXX this needs to be concurrent
839-- | Like 'scanl1'' but with a monadic step function.
840--
841-- @since 0.6.0
842{-# INLINE scanl1M' #-}
843scanl1M' :: (IsStream t, Monad m) => (a -> a -> m a) -> t m a -> t m a
844scanl1M' step m = fromStreamD $ D.scanl1M' step $ toStreamD m
846-- | Like 'scanl'' but for a non-empty stream. The first element of the stream
847-- is used as the initial value of the accumulator. Does nothing if the stream
848-- is empty.
849--
850-- @
851-- >>> Stream.toList $ Stream.scanl1' (+) $ fromList [1,2,3,4]
852-- [1,3,6,10]
853--
854-- @
855--
856-- @since 0.6.0
857{-# INLINE scanl1' #-}
858scanl1' :: (IsStream t, Monad m) => (a -> a -> a) -> t m a -> t m a
859scanl1' step m = fromStreamD $ D.scanl1' step $ toStreamD m
861------------------------------------------------------------------------------
862-- Filtering
863------------------------------------------------------------------------------
865-- | Modify a @t m a -> t m a@ stream transformation that accepts a predicate
866-- @(a -> b)@ to accept @((s, a) -> b)@ instead, provided a transformation @t m
867-- a -> t m (s, a)@. Convenient to filter with index or time.
868--
869-- @
870-- filterWithIndex = with indexed filter
871-- filterWithAbsTime = with timestamped filter
872-- filterWithRelTime = with timeIndexed filter
873-- @
874--
875-- /Pre-release/
876{-# INLINE with #-}
877with :: forall (t :: (Type -> Type) -> Type -> Type) m a b s. Functor (t m) =>
878 (t m a -> t m (s, a))
879 -> (((s, a) -> b) -> t m (s, a) -> t m (s, a))
880 -> (((s, a) -> b) -> t m a -> t m a)
881with f comb g = fmap snd . comb g . f
883-- | Include only those elements that pass a predicate.
884--
885-- @since 0.1.0
886{-# INLINE filter #-}
887#if __GLASGOW_HASKELL__ != 802
888-- GHC 8.2.2 crashes with this code, when used with "stack"
889filter :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m a
890filter p m = fromStreamS $ S.filter p $ toStreamS m
891#else
892filter :: IsStream t => (a -> Bool) -> t m a -> t m a
893filter p m = fromStream $ K.filter p $ toStream m
894#endif
896-- | Same as 'filter' but with a monadic predicate.
897--
898-- @since 0.4.0
899{-# INLINE filterM #-}
900filterM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
901filterM p m = fromStreamD $ D.filterM p $ toStreamD m
903-- | Drop repeated elements that are adjacent to each other using the supplied
904-- comparison function.
905--
906-- @uniq = uniqBy (==)
907--
908-- To strip duplicate path separators:
909--
910-- @
911-- f x y = x == '/' && x == y
912-- Stream.toList $ Stream.uniqBy f $ Stream.fromList "//a//b"
913-- "/a/b"
914-- @
915--
916-- Space: @O(1)@
917--
918-- See also: 'nubBy'.
919--
920-- /Pre-release/
921--
922{-# INLINE uniqBy #-}
923uniqBy :: (IsStream t, Monad m, Functor (t m)) =>
924 (a -> a -> Bool) -> t m a -> t m a
925uniqBy eq = catMaybes . rollingMap f
927 where
929 f pre curr =
930 case pre of
931 Nothing -> Just curr
932 Just x -> if x `eq` curr then Nothing else Just curr
934-- | Drop repeated elements that are adjacent to each other.
935--
936-- @since 0.6.0
937{-# INLINE uniq #-}
938uniq :: (Eq a, IsStream t, Monad m) => t m a -> t m a
939uniq = fromStreamD . D.uniq . toStreamD
941-- | Strip all leading and trailing occurrences of an element passing a
942-- predicate and make all other consecutive occurrences uniq.
943--
944-- @
945-- prune p = dropWhileAround p $ uniqBy (x y -> p x && p y)
946-- @
947--
948-- @
949-- > Stream.prune isSpace (Stream.fromList " hello world! ")
950-- "hello world!"
951--
952-- @
953--
954-- Space: @O(1)@
955--
956-- /Unimplemented/
957{-# INLINE prune #-}
958prune ::
959 -- (IsStream t, Monad m, Eq a) =>
960 (a -> Bool) -> t m a -> t m a
961prune = error "Not implemented yet!"
963-- Possible implementation:
964-- @repeated =
965-- Stream.catMaybes . Stream.parseMany (Parser.groupBy (==) Fold.repeated)@
966--
967-- 'Fold.repeated' should return 'Just' when repeated, and 'Nothing' for a
968-- single element.
969--
970-- | Emit only repeated elements, once.
971--
972-- /Unimplemented/
973repeated :: -- (IsStream t, Monad m, Eq a) =>
974 t m a -> t m a
975repeated = undefined
977-- We can have more efficient implementations for nubOrd and nubInt by using
978-- Set and IntSet to find/remove duplication. For Hashable we can use a
979-- hashmap. Use rewrite rules to specialize to more efficient impls.
980--
981-- | Drop repeated elements anywhere in the stream.
982--
983-- /Caution: not scalable for infinite streams/
984--
985-- /See also: nubWindowBy/
986--
987-- /Unimplemented/
988--
989{-# INLINE nubBy #-}
990nubBy :: -- (IsStream t, Monad m) =>
991 (a -> a -> Bool) -> t m a -> t m a
992nubBy = undefined -- fromStreamD . D.nubBy . toStreamD
994-- | Drop repeated elements within the specified tumbling window in the stream.
995--
996-- @nubBy = nubWindowBy maxBound@
997--
998-- /Unimplemented/
999--
1000{-# INLINE nubWindowBy #-}
1001nubWindowBy :: -- (IsStream t, Monad m) =>
1002 Int -> (a -> a -> Bool) -> t m a -> t m a
1003nubWindowBy = undefined -- fromStreamD . D.nubWithinBy . toStreamD
1005-- | Deletes the first occurrence of the element in the stream that satisfies
1006-- the given equality predicate.
1008-- @
1009-- >>> Stream.toList $ Stream.deleteBy (==) 3 $ Stream.fromList [1,3,3,5]
1010-- [1,3,5]
1012-- @
1014-- @since 0.6.0
1015{-# INLINE deleteBy #-}
1016deleteBy :: (IsStream t, Monad m) => (a -> a -> Bool) -> a -> t m a -> t m a
1017deleteBy cmp x m = fromStreamS $ S.deleteBy cmp x (toStreamS m)
1019------------------------------------------------------------------------------
1020-- Lossy Buffering
1021------------------------------------------------------------------------------
1023-- XXX We could use 'maxBuffer Block/Drop/Rotate/Sample' instead. However we
1024-- may want to have the evaluation rate independent of the sampling rate. To
1025-- support that we can decouple evaluation and sampling in independent stages.
1026-- The sampling stage would strictly evaluate and sample, the evaluation stage
1027-- would control the evaluation rate.
1029-- | Evaluate the input stream continuously and keep only the oldest @n@
1030-- elements in the buffer, discard the new ones when the buffer is full. When
1031-- the output stream is evaluated it consumes the values from the buffer in a
1032-- FIFO manner.
1034-- /Unimplemented/
1036{-# INLINE sampleOld #-}
1037sampleOld :: -- (IsStream t, Monad m) =>
1038 Int -> t m a -> t m a
1039sampleOld = undefined
1041-- | Evaluate the input stream continuously and keep only the latest @n@
1042-- elements in a ring buffer, keep discarding the older ones to make space for
1043-- the new ones. When the output stream is evaluated it consumes the values
1044-- from the buffer in a FIFO manner.
1046-- /Unimplemented/
1048{-# INLINE sampleNew #-}
1049sampleNew :: -- (IsStream t, Monad m) =>
1050 Int -> t m a -> t m a
1051sampleNew = undefined
1053-- | Like 'sampleNew' but samples at uniform intervals to match the consumer
1054-- rate. Note that 'sampleNew' leads to non-uniform sampling depending on the
1055-- consumer pattern.
1057-- /Unimplemented/
1059{-# INLINE sampleRate #-}
1060sampleRate :: -- (IsStream t, Monad m) =>
1061 Double -> t m a -> t m a
1062sampleRate = undefined
1064------------------------------------------------------------------------------
1065-- Trimming
1066------------------------------------------------------------------------------
1068-- | Same as 'takeWhile' but with a monadic predicate.
1070-- @since 0.4.0
1071{-# INLINE takeWhileM #-}
1072takeWhileM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
1073takeWhileM p m = fromStreamD $ D.takeWhileM p $ toStreamD m
1075-- See the lastN fold for impl hints. Use a Data.Array based ring buffer.
1077-- takeLast n = Stream.concatM . fmap Array.toStream . fold Fold.lastN
1079-- | Take @n@ elements at the end of the stream.
1081-- O(n) space, where n is the number elements taken.
1083-- /Unimplemented/
1084{-# INLINE takeLast #-}
1085takeLast :: -- (IsStream t, Monad m) =>
1086 Int -> t m a -> t m a
1087takeLast = undefined -- fromStreamD $ D.takeLast n $ toStreamD m
1089-- | Take time interval @i@ seconds at the end of the stream.
1091-- O(n) space, where n is the number elements taken.
1093-- /Unimplemented/
1094{-# INLINE takeLastInterval #-}
1095takeLastInterval :: -- (IsStream t, Monad m) =>
1096 Double -> t m a -> t m a
1097takeLastInterval = undefined -- fromStreamD $ D.takeLast n $ toStreamD m
1099-- | Take all consecutive elements at the end of the stream for which the
1100-- predicate is true.
1102-- O(n) space, where n is the number elements taken.
1104-- /Unimplemented/
1105{-# INLINE takeWhileLast #-}
1106takeWhileLast :: -- (IsStream t, Monad m) =>
1107 (a -> Bool) -> t m a -> t m a
1108takeWhileLast = undefined -- fromStreamD $ D.takeWhileLast n $ toStreamD m
1110-- | Like 'takeWhile' and 'takeWhileLast' combined.
1112-- O(n) space, where n is the number elements taken from the end.
1114-- /Unimplemented/
1115{-# INLINE takeWhileAround #-}
1116takeWhileAround :: -- (IsStream t, Monad m) =>
1117 (a -> Bool) -> t m a -> t m a
1118takeWhileAround = undefined -- fromStreamD $ D.takeWhileAround n $ toStreamD m
1120-- | @takeInterval duration@ yields stream elements upto specified time
1121-- @duration@. The duration starts when the stream is evaluated for the first
1122-- time, before the first element is yielded. The time duration is checked
1123-- before generating each element, if the duration has expired the stream
1124-- stops.
1126-- The total time taken in executing the stream is guaranteed to be /at least/
1127-- @duration@, however, because the duration is checked before generating an
1128-- element, the upper bound is indeterminate and depends on the time taken in
1129-- generating and processing the last element.
1131-- No element is yielded if the duration is zero. At least one element is
1132-- yielded if the duration is non-zero.
1134-- /Pre-release/
1136{-# INLINE takeInterval #-}
1137takeInterval ::(MonadIO m, IsStream t, TimeUnit64 d) => d -> t m a -> t m a
1138takeInterval d = fromStreamD . D.takeByTime d . toStreamD
1140-- | Drop elements in the stream as long as the predicate succeeds and then
1141-- take the rest of the stream.
1143-- @since 0.1.0
1144{-# INLINE dropWhile #-}
1145dropWhile :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m a
1146dropWhile p m = fromStreamS $ S.dropWhile p $ toStreamS m
1148-- | Same as 'dropWhile' but with a monadic predicate.
1150-- @since 0.4.0
1151{-# INLINE dropWhileM #-}
1152dropWhileM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
1153dropWhileM p m = fromStreamD $ D.dropWhileM p $ toStreamD m
1155-- | @dropInterval duration@ drops stream elements until specified @duration@ has
1156-- passed. The duration begins when the stream is evaluated for the first
1157-- time. The time duration is checked /after/ generating a stream element, the
1158-- element is yielded if the duration has expired otherwise it is dropped.
1160-- The time elapsed before starting to generate the first element is /at most/
1161-- @duration@, however, because the duration expiry is checked after the
1162-- element is generated, the lower bound is indeterminate and depends on the
1163-- time taken in generating an element.
1165-- All elements are yielded if the duration is zero.
1167-- /Pre-release/
1169{-# INLINE dropInterval #-}
1170dropInterval ::(MonadIO m, IsStream t, TimeUnit64 d) => d -> t m a -> t m a
1171dropInterval d = fromStreamD . D.dropByTime d . toStreamD
1173-- | Drop @n@ elements at the end of the stream.
1175-- O(n) space, where n is the number elements dropped.
1177-- /Unimplemented/
1178{-# INLINE dropLast #-}
1179dropLast :: -- (IsStream t, Monad m) =>
1180 Int -> t m a -> t m a
1181dropLast = undefined -- fromStreamD $ D.dropLast n $ toStreamD m
1183-- | Drop time interval @i@ seconds at the end of the stream.
1185-- O(n) space, where n is the number elements dropped.
1187-- /Unimplemented/
1188{-# INLINE dropLastInterval #-}
1189dropLastInterval :: -- (IsStream t, Monad m) =>
1190 Int -> t m a -> t m a
1191dropLastInterval = undefined
1193-- | Drop all consecutive elements at the end of the stream for which the
1194-- predicate is true.
1196-- O(n) space, where n is the number elements dropped.
1198-- /Unimplemented/
1199{-# INLINE dropWhileLast #-}
1200dropWhileLast :: -- (IsStream t, Monad m) =>
1201 (a -> Bool) -> t m a -> t m a
1202dropWhileLast = undefined -- fromStreamD $ D.dropWhileLast n $ toStreamD m
1204-- | Like 'dropWhile' and 'dropWhileLast' combined.
1206-- O(n) space, where n is the number elements dropped from the end.
1208-- /Unimplemented/
1209{-# INLINE dropWhileAround #-}
1210dropWhileAround :: -- (IsStream t, Monad m) =>
1211 (a -> Bool) -> t m a -> t m a
1212dropWhileAround = undefined -- fromStreamD $ D.dropWhileAround n $ toStreamD m
1214------------------------------------------------------------------------------
1215-- Inserting Elements
1216------------------------------------------------------------------------------
1218-- | @insertBy cmp elem stream@ inserts @elem@ before the first element in
1219-- @stream@ that is less than @elem@ when compared using @cmp@.
1221-- @
1222-- insertBy cmp x = 'mergeBy' cmp ('fromPure' x)
1223-- @
1225-- @
1226-- >>> Stream.toList $ Stream.insertBy compare 2 $ Stream.fromList [1,3,5]
1227-- [1,2,3,5]
1229-- @
1231-- @since 0.6.0
1232{-# INLINE insertBy #-}
1233insertBy ::
1234 (IsStream t, Monad m) => (a -> a -> Ordering) -> a -> t m a -> t m a
1235insertBy cmp x m = fromStreamS $ S.insertBy cmp x (toStreamS m)
1237-- | Insert a pure value between successive elements of a stream.
1239-- >>> Stream.toList $ Stream.intersperse ',' $ Stream.fromList "hello"
1240-- "h,e,l,l,o"
1242-- @since 0.7.0
1243{-# INLINE intersperse #-}
1244intersperse :: (IsStream t, MonadAsync m) => a -> t m a -> t m a
1245intersperse a = fromStreamS . S.intersperse a . toStreamS
1247-- | Insert a side effect before consuming an element of a stream except the
1248-- first one.
1250-- >>> Stream.drain $ Stream.trace putChar $ Stream.intersperseM_ (putChar '.') $ Stream.fromList "hello"
1251-- h.e.l.l.o
1253-- /Pre-release/
1254{-# INLINE intersperseM_ #-}
1255intersperseM_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
1256intersperseM_ m = fromStreamD . D.intersperseM_ m . toStreamD
1258-- | Intersperse a monadic action into the input stream after every @n@
1259-- elements.
1261-- @
1262-- > Stream.toList $ Stream.intersperseBySpan 2 (return ',') $ Stream.fromList "hello"
1263-- "he,ll,o"
1265-- @
1267-- /Unimplemented/
1268{-# INLINE intersperseBySpan #-}
1269intersperseBySpan :: -- IsStream t =>
1270 Int -> m a -> t m a -> t m a
1271intersperseBySpan _n _f _xs = undefined
1273-- | Insert an effect and its output after consuming an element of a stream.
1275-- >>> Stream.toList $ Stream.trace putChar $ intersperseSuffix (putChar '.' >> return ',') $ Stream.fromList "hello"
1276-- h.,e.,l.,l.,o.,"h,e,l,l,o,"
1278-- /Pre-release/
1279{-# INLINE intersperseSuffix #-}
1280intersperseSuffix :: (IsStream t, Monad m) => m a -> t m a -> t m a
1281intersperseSuffix m = fromStreamD . D.intersperseSuffix m . toStreamD
1283-- | Insert a side effect after consuming an element of a stream.
1285-- @
1286-- >>> Stream.mapM_ putChar $ Stream.intersperseSuffix_ (threadDelay 1000000) $ Stream.fromList "hello"
1287-- hello
1289-- @
1291-- /Pre-release/
1293{-# INLINE intersperseSuffix_ #-}
1294intersperseSuffix_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
1295intersperseSuffix_ m = fromStreamD . D.intersperseSuffix_ m . toStreamD
1297-- XXX Use an offset argument, like tapOffsetEvery
1299-- | Like 'intersperseSuffix' but intersperses an effectful action into the
1300-- input stream after every @n@ elements and after the last element.
1302-- >>> Stream.toList $ Stream.intersperseSuffixBySpan 2 (return ',') $ Stream.fromList "hello"
1303-- "he,ll,o,"
1305-- /Pre-release/
1307{-# INLINE intersperseSuffixBySpan #-}
1308intersperseSuffixBySpan :: (IsStream t, Monad m)
1309 => Int -> m a -> t m a -> t m a
1310intersperseSuffixBySpan n eff =
1311 fromStreamD . D.intersperseSuffixBySpan n eff . toStreamD
1313-- | Insert a side effect before consuming an element of a stream.
1315-- >>> Stream.toList $ Stream.trace putChar $ Stream.interspersePrefix_ (putChar '.' >> return ',') $ Stream.fromList "hello"
1316-- .h.e.l.l.o"hello"
1318-- Same as 'trace_' but may be concurrent.
1320-- /Concurrent/
1322-- /Pre-release/
1324{-# INLINE interspersePrefix_ #-}
1325interspersePrefix_ :: (IsStream t, MonadAsync m) => m b -> t m a -> t m a
1326interspersePrefix_ m = mapM (\x -> void m >> return x)
1328------------------------------------------------------------------------------
1329-- Inserting Time
1330------------------------------------------------------------------------------
1332-- Note: delay must be serial.
1334-- | Introduce a delay of specified seconds before consuming an element of the
1335-- stream except the first one.
1337-- >>> Stream.mapM_ print $ Stream.timestamped $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
1338-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),1)
1339-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),2)
1340-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),3)
1342-- @since 0.8.0
1344{-# INLINE delay #-}
1345delay :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
1346delay n = intersperseM_ $ liftIO $ threadDelay $ round $ n * 1000000
1348-- Note: delay must be serial.
1350-- | Introduce a delay of specified seconds after consuming an element of a
1351-- stream.
1353-- >>> Stream.mapM_ print $ Stream.timestamped $ Stream.delayPost 1 $ Stream.enumerateFromTo 1 3
1354-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),1)
1355-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),2)
1356-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),3)
1358-- /Pre-release/
1360{-# INLINE delayPost #-}
1361delayPost :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
1362delayPost n = intersperseSuffix_ $ liftIO $ threadDelay $ round $ n * 1000000
1364-- Note: delay must be serial, that's why 'trace_' is used.
1366-- | Introduce a delay of specified seconds before consuming an element of a
1367-- stream.
1369-- >>> Stream.mapM_ print $ Stream.timestamped $ Stream.delayPre 1 $ Stream.enumerateFromTo 1 3
1370-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),1)
1371-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),2)
1372-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),3)
1374-- /Pre-release/
1376{-# INLINE delayPre #-}
1377delayPre :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
1378delayPre n = trace_ $ liftIO $ threadDelay $ round $ n * 1000000
1380------------------------------------------------------------------------------
1381-- Reorder in sequence
1382------------------------------------------------------------------------------
1384-- | Buffer until the next element in sequence arrives. The function argument
1385-- determines the difference in sequence numbers. This could be useful in
1386-- implementing sequenced streams, for example, TCP reassembly.
1388-- /Unimplemented/
1390{-# INLINE reassembleBy #-}
1391reassembleBy
1392 :: -- (IsStream t, Monad m) =>
1393 Fold m a b
1394 -> (a -> a -> Int)
1395 -> t m a
1396 -> t m b
1397reassembleBy = undefined
1399------------------------------------------------------------------------------
1400-- Position Indexing
1401------------------------------------------------------------------------------
1403-- |
1404-- > indexed = Stream.postscanl' (\(i, _) x -> (i + 1, x)) (-1,undefined)
1405-- > indexed = Stream.zipWith (,) (Stream.enumerateFrom 0)
1407-- Pair each element in a stream with its index, starting from index 0.
1409-- >>> Stream.toList $ Stream.indexed $ Stream.fromList "hello"
1410-- [(0,'h'),(1,'e'),(2,'l'),(3,'l'),(4,'o')]
1412-- @since 0.6.0
1413{-# INLINE indexed #-}
1414indexed :: (IsStream t, Monad m) => t m a -> t m (Int, a)
1415indexed = fromStreamD . D.indexed . toStreamD
1417-- |
1418-- > indexedR n = Stream.postscanl' (\(i, _) x -> (i - 1, x)) (n + 1,undefined)
1419-- > indexedR n = Stream.zipWith (,) (Stream.enumerateFromThen n (n - 1))
1421-- Pair each element in a stream with its index, starting from the
1422-- given index @n@ and counting down.
1424-- >>> Stream.toList $ Stream.indexedR 10 $ Stream.fromList "hello"
1425-- [(10,'h'),(9,'e'),(8,'l'),(7,'l'),(6,'o')]
1427-- @since 0.6.0
1428{-# INLINE indexedR #-}
1429indexedR :: (IsStream t, Monad m) => Int -> t m a -> t m (Int, a)
1430indexedR n = fromStreamD . D.indexedR n . toStreamD
1432-------------------------------------------------------------------------------
1433-- Time Indexing
1434-------------------------------------------------------------------------------
1436-- Note: The timestamp stream must be the second stream in the zip so that the
1437-- timestamp is generated after generating the stream element and not before.
1438-- If we do not do that then the following example will generate the same
1439-- timestamp for first two elements:
1441-- Stream.mapM_ print $ Stream.timestamped $ Stream.delay $ Stream.enumerateFromTo 1 3
1443-- | Pair each element in a stream with an absolute timestamp, using a clock of
1444-- specified granularity. The timestamp is generated just before the element
1445-- is consumed.
1447-- >>> Stream.mapM_ print $ Stream.timestampWith 0.01 $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
1448-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),1)
1449-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),2)
1450-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),3)
1452-- /Pre-release/
1454{-# INLINE timestampWith #-}
1455timestampWith :: (IsStream t, MonadAsync m, Functor (t m))
1456 => Double -> t m a -> t m (AbsTime, a)
1457timestampWith g stream = zipWith (flip (,)) stream (absTimesWith g)
1459-- TBD: check performance vs a custom implementation without using zipWith.
1461-- /Pre-release/
1463{-# INLINE timestamped #-}
1464timestamped :: (IsStream t, MonadAsync m, Functor (t m))
1465 => t m a -> t m (AbsTime, a)
1466timestamped = timestampWith 0.01
1468-- | Pair each element in a stream with relative times starting from 0, using a
1469-- clock with the specified granularity. The time is measured just before the
1470-- element is consumed.
1472-- >>> Stream.mapM_ print $ Stream.timeIndexWith 0.01 $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
1473-- (RelTime64 (NanoSecond64 ...),1)
1474-- (RelTime64 (NanoSecond64 ...),2)
1475-- (RelTime64 (NanoSecond64 ...),3)
1477-- /Pre-release/
1479{-# INLINE timeIndexWith #-}
1480timeIndexWith :: (IsStream t, MonadAsync m, Functor (t m))
1481 => Double -> t m a -> t m (RelTime64, a)
1482timeIndexWith g stream = zipWith (flip (,)) stream (relTimesWith g)
1484-- | Pair each element in a stream with relative times starting from 0, using a
1485-- 10 ms granularity clock. The time is measured just before the element is
1486-- consumed.
1488-- >>> Stream.mapM_ print $ Stream.timeIndexed $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
1489-- (RelTime64 (NanoSecond64 ...),1)
1490-- (RelTime64 (NanoSecond64 ...),2)
1491-- (RelTime64 (NanoSecond64 ...),3)
1493-- /Pre-release/
1495{-# INLINE timeIndexed #-}
1496timeIndexed :: (IsStream t, MonadAsync m, Functor (t m))
1497 => t m a -> t m (RelTime64, a)
1498timeIndexed = timeIndexWith 0.01
1500------------------------------------------------------------------------------
1501-- Searching
1502------------------------------------------------------------------------------
1504-- | Find all the indices where the value of the element in the stream is equal
1505-- to the given value.
1507-- > elemIndices a = findIndices (== a)
1509-- @since 0.5.0
1510{-# INLINE elemIndices #-}
1511elemIndices :: (IsStream t, Eq a, Monad m) => a -> t m a -> t m Int
1512elemIndices a = findIndices (== a)
1514------------------------------------------------------------------------------
1515-- Rolling map
1516------------------------------------------------------------------------------
1518-- XXX this is not a one-to-one map so calling it map may not be right.
1519-- We can perhaps call it zipWithTail or rollWith.
1521-- | Apply a function on every two successive elements of a stream. The first
1522-- argument of the map function is the previous element and the second argument
1523-- is the current element. When the current element is the first element, the
1524-- previous element is 'Nothing'.
1526-- /Pre-release/
1528{-# INLINE rollingMap #-}
1529rollingMap :: (IsStream t, Monad m) => (Maybe a -> a -> b) -> t m a -> t m b
1530rollingMap f m = fromStreamD $ D.rollingMap f $ toStreamD m
1532-- | Like 'rollingMap' but with an effectful map function.
1534-- /Pre-release/
1536{-# INLINE rollingMapM #-}
1537rollingMapM :: (IsStream t, Monad m) => (Maybe a -> a -> m b) -> t m a -> t m b
1538rollingMapM f m = fromStreamD $ D.rollingMapM f $ toStreamD m
1540-- | Like 'rollingMap' but requires at least two elements in the stream,
1541-- returns an empty stream otherwise.
1543-- This is the stream equivalent of the list idiom @zipWith f xs (tail xs)@.
1545-- /Pre-release/
1547{-# INLINE rollingMap2 #-}
1548rollingMap2 :: (IsStream t, Monad m) => (a -> a -> b) -> t m a -> t m b
1549rollingMap2 f m = fromStreamD $ D.rollingMap2 f $ toStreamD m
1551------------------------------------------------------------------------------
1552-- Maybe Streams
1553------------------------------------------------------------------------------
1555-- | Map a 'Maybe' returning function to a stream, filter out the 'Nothing'
1556-- elements, and return a stream of values extracted from 'Just'.
1558-- Equivalent to:
1560-- @
1561-- mapMaybe f = Stream.map 'fromJust' . Stream.filter 'isJust' . Stream.map f
1562-- @
1564-- @since 0.3.0
1565{-# INLINE mapMaybe #-}
1566mapMaybe :: (IsStream t, Monad m) => (a -> Maybe b) -> t m a -> t m b
1567mapMaybe f m = fromStreamS $ S.mapMaybe f $ toStreamS m
1569-- | Like 'mapMaybe' but maps a monadic function.
1571-- Equivalent to:
1573-- @
1574-- mapMaybeM f = Stream.map 'fromJust' . Stream.filter 'isJust' . Stream.mapM f
1575-- @
1577-- /Concurrent (do not use with 'fromParallel' on infinite streams)/
1579-- @since 0.3.0
1580{-# INLINE_EARLY mapMaybeM #-}
1581mapMaybeM :: (IsStream t, MonadAsync m, Functor (t m))
1582 => (a -> m (Maybe b)) -> t m a -> t m b
1583mapMaybeM f = fmap fromJust . filter isJust . mapM f
1585{-# RULES "mapMaybeM serial" mapMaybeM = mapMaybeMSerial #-}
1586{-# INLINE mapMaybeMSerial #-}
1587mapMaybeMSerial :: Monad m => (a -> m (Maybe b)) -> SerialT m a -> SerialT m b
1588mapMaybeMSerial f m = fromStreamD $ D.mapMaybeM f $ toStreamD m
1590-- | In a stream of 'Maybe's, discard 'Nothing's and unwrap 'Just's.
1592-- /Pre-release/
1594{-# INLINE catMaybes #-}
1595catMaybes :: (IsStream t, Monad m, Functor (t m)) => t m (Maybe a) -> t m a
1596catMaybes = fmap fromJust . filter isJust
1598------------------------------------------------------------------------------
1599-- Either streams
1600------------------------------------------------------------------------------
1602-- | Discard 'Right's and unwrap 'Left's in an 'Either' stream.
1604-- /Pre-release/
1606{-# INLINE lefts #-}
1607lefts :: (IsStream t, Monad m, Functor (t m)) => t m (Either a b) -> t m a
1608lefts = fmap (fromLeft undefined) . filter isLeft
1610-- | Discard 'Left's and unwrap 'Right's in an 'Either' stream.
1612-- /Pre-release/
1614{-# INLINE rights #-}
1615rights :: (IsStream t, Monad m, Functor (t m)) => t m (Either a b) -> t m b
1616rights = fmap (fromRight undefined) . filter isRight
1618-- | Remove the either wrapper and flatten both lefts and as well as rights in
1619-- the output stream.
1621-- /Pre-release/
1623{-# INLINE both #-}
1624both :: Functor (t m) => t m (Either a a) -> t m a
1625both = fmap (either id id)
1627------------------------------------------------------------------------------
1628-- Concurrent Application
1629------------------------------------------------------------------------------
1631-- | Parallel transform application operator; applies a stream transformation
1632-- function @t m a -> t m b@ to a stream @t m a@ concurrently; the input stream
1633-- is evaluated asynchronously in an independent thread yielding elements to a
1634-- buffer and the transformation function runs in another thread consuming the
1635-- input from the buffer. '|$' is just like regular function application
1636-- operator '$' except that it is concurrent.
1638-- If you read the signature as @(t m a -> t m b) -> (t m a -> t m b)@ you can
1639-- look at it as a transformation that converts a transform function to a
1640-- buffered concurrent transform function.
1642-- The following code prints a value every second even though each stage adds a
1643-- 1 second delay.
1646-- >>> :{
1647-- Stream.drain $
1648-- Stream.mapM (\x -> threadDelay 1000000 >> print x)
1649-- |$ Stream.replicateM 3 (threadDelay 1000000 >> return 1)
1650-- :}
1651-- 1
1652-- 1
1653-- 1
1655-- /Concurrent/
1657-- /Since: 0.3.0 ("Streamly")/
1659-- @since 0.8.0
1660{-# INLINE (|$) #-}
1661(|$) :: (IsStream t, MonadAsync m) => (t m a -> t m b) -> (t m a -> t m b)
1662-- (|$) f = f . mkAsync
1663(|$) f = f . mkParallel
1665infixr 0 |$
1667-- | Same as '|$'.
1669-- /Internal/
1671{-# INLINE applyAsync #-}
1672applyAsync :: (IsStream t, MonadAsync m)
1673 => (t m a -> t m b) -> (t m a -> t m b)
1674applyAsync = (|$)
1676-- | Same as '|$' but with arguments reversed.
1678-- (|&) = flip (|$)
1680-- /Concurrent/
1682-- /Since: 0.3.0 ("Streamly")/
1684-- @since 0.8.0
1685{-# INLINE (|&) #-}
1686(|&) :: (IsStream t, MonadAsync m) => t m a -> (t m a -> t m b) -> t m b
1687x |& f = f |$ x
1689infixl 1 |&