on d2aaef0 help sign in
1628 lines 51 kB history raw
1-- |
2-- Module : Streamly.Internal.Data.Stream.IsStream.Transform
3-- Copyright : (c) 2017 Composewell Technologies
4-- License : BSD-3-Clause
5-- Maintainer : streamly@composewell.com
6-- Stability : experimental
7-- Portability : GHC
9module Streamly.Internal.Data.Stream.IsStream.Transform
10 (
11 -- * Piping
12 -- | Pass through a 'Pipe'.
13 transform
15 -- * Folding
16 , foldrS
17 , foldrSShared
18 , foldrT
20 -- * Mapping
21 -- | Stateless one-to-one maps.
22 , map
23 , sequence
24 , mapM
25 , smapM
27 -- * Mapping Side Effects (Observation)
28 -- | See also the intersperse*_ combinators.
29 , trace
30 , trace_
31 , tap
32 , tapOffsetEvery
33 , tapAsync
34 , tapAsyncK
35 , distributeAsync_
36 , pollCounts
38 -- * Scanning By 'Fold'
39 , scan
40 , scanMany
41 , postscan
43 -- * Scanning
44 -- | Left scans. Stateful, mostly one-to-one maps.
45 , scanl'
46 , scanlM'
47 , scanlMAfter'
48 , postscanlMAfter'
49 , postscanl'
50 , postscanlM'
51 , prescanl'
52 , prescanlM'
53 , scanl1'
54 , scanl1M'
56 -- XXX Once we have pipes the contravariant transformations can be
57 -- represented by attaching pipes before a transformation.
58 --
59 -- , lscanl'
60 -- , lscanlM'
61 -- , lscanl1'
62 -- , lscanl1M'
63 --
64 -- , lpostscanl'
65 -- , lpostscanlM'
66 -- , lprescanl'
67 -- , lprescanlM'
69 -- * Filtering
70 -- | Produce a subset of the stream using criteria based on the values of
71 -- the elements. We can use a concatMap and scan for filtering but these
72 -- combinators are more efficient and convenient.
74 , with
75 , deleteBy
76 , filter
77 , filterM
78 , uniq
79 , uniqBy
80 , nubBy
81 , 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.IO.Class (MonadIO(..))
219import Control.Monad.Trans.Class (MonadTrans(..))
220import Data.Either (isLeft, isRight, fromLeft, fromRight)
221import Data.Kind (Type)
222import Data.Maybe (isJust, fromJust)
223import Streamly.Internal.Data.Fold.Type (Fold (..))
224import Streamly.Internal.Data.Pipe.Type (Pipe (..))
225import Streamly.Internal.Data.Stream.IsStream.Combinators
226 ( inspectMode, maxBuffer, maxThreads, rate, avgRate, minRate
227 , maxRate, constRate)
228import Streamly.Internal.Data.Stream.IsStream.Common
229 ( absTimesWith
230 , drop
231 , findIndices
232 , map
233 , postscanlM'
234 , relTimesWith
235 , reverse
236 , reverse'
237 , scanlMAfter'
238 , postscanlMAfter'
239 , smapM
240 , take
241 , takeWhile
242 , interjectSuffix
243 , intersperseM
244 , mkAsync
245 , mkParallel
246 , zipWith
247 )
248import Streamly.Internal.Control.Concurrent (MonadAsync)
249import Streamly.Internal.Data.Stream.IsStream.Type
250 (IsStream(..), fromStreamS, toStreamS, fromStreamD, toStreamD, toConsK)
251import Streamly.Internal.Data.Stream.Serial (SerialT)
252import Streamly.Internal.Data.SVar (Rate(..))
253import Streamly.Internal.Data.Time.Units (TimeUnit64, AbsTime, RelTime64)
255import qualified Streamly.Internal.Data.Fold as FL
256import qualified Streamly.Internal.Data.Stream.Parallel as Par
257import qualified Streamly.Internal.Data.Stream.Serial as Serial
258import qualified Streamly.Internal.Data.Stream.StreamD as D
259import qualified Streamly.Internal.Data.Stream.StreamK.Type as K
260#ifdef USE_STREAMK_ONLY
261import qualified Streamly.Internal.Data.Stream.StreamK as S
262#else
263import qualified Streamly.Internal.Data.Stream.StreamD as S
264#endif
265import qualified Prelude
267import Prelude hiding
268 ( filter, drop, dropWhile, take, takeWhile, foldr, map, mapM, sequence
269 , reverse, foldr1 , scanl, scanl1, zipWith)
271--
272-- $setup
273-- >>> :m
274-- >>> import Control.Concurrent (threadDelay)
275-- >>> import Data.Function ((&))
276-- >>> import Streamly.Prelude ((|$))
277-- >>> import Prelude hiding ( filter, drop, dropWhile, take, takeWhile, foldr, map, mapM, sequence, reverse, foldr1 , scanl, scanl1)
278-- >>> import qualified Streamly.Prelude as Stream
279-- >>> import Streamly.Internal.Data.Stream.IsStream as Stream
280-- >>> import qualified Streamly.Data.Fold as Fold
281-- >>> import qualified Streamly.Internal.Data.Fold as Fold
282-- >>> import System.IO (stdout, hSetBuffering, BufferMode(LineBuffering))
283--
284-- >>> hSetBuffering stdout LineBuffering
286------------------------------------------------------------------------------
287-- Piping
288------------------------------------------------------------------------------
290-- | Use a 'Pipe' to transform a stream.
291--
292-- /Pre-release/
293--
294{-# INLINE transform #-}
295transform :: (IsStream t, Monad m) => Pipe m a b -> t m a -> t m b
296transform pipe xs = fromStreamD $ D.transform pipe (toStreamD xs)
298------------------------------------------------------------------------------
299-- Transformation Folds
300------------------------------------------------------------------------------
302-- | Right fold to a streaming monad.
303--
304-- > foldrS Stream.cons Stream.nil === id
305--
306-- 'foldrS' can be used to perform stateless stream to stream transformations
307-- like map and filter in general. It can be coupled with a scan to perform
308-- stateful transformations. However, note that the custom map and filter
309-- routines can be much more efficient than this due to better stream fusion.
310--
311-- >>> Stream.toList $ Stream.foldrS Stream.cons Stream.nil $ Stream.fromList [1..5]
312-- [1,2,3,4,5]
313--
314-- Find if any element in the stream is 'True':
315--
316-- >>> Stream.toList $ Stream.foldrS (\x xs -> if odd x then return True else xs) (return False) $ (Stream.fromList (2:4:5:undefined) :: Stream.SerialT IO Int)
317-- [True]
318--
319-- Map (+2) on odd elements and filter out the even elements:
320--
321-- >>> Stream.toList $ Stream.foldrS (\x xs -> if odd x then (x + 2) `Stream.cons` xs else xs) Stream.nil $ (Stream.fromList [1..5] :: Stream.SerialT IO Int)
322-- [3,5,7]
323--
324-- 'foldrM' can also be represented in terms of 'foldrS', however, the former
325-- is much more efficient:
326--
327-- > foldrM f z s = runIdentityT $ foldrS (\x xs -> lift $ f x (runIdentityT xs)) (lift z) s
328--
329-- /Pre-release/
330{-# INLINE foldrS #-}
331foldrS :: IsStream t => (a -> t m b -> t m b) -> t m b -> t m a -> t m b
332foldrS f z xs =
333 fromStream
334 $ K.foldrS
335 (\y ys -> toStream $ f y (fromStream ys))
336 (toStream z)
337 (toStream xs)
339{-# INLINE foldrSShared #-}
340foldrSShared :: IsStream t => (a -> t m b -> t m b) -> t m b -> t m a -> t m b
341foldrSShared f z xs =
342 fromStream
343 $ K.foldrSShared
344 (\y ys -> toStream $ f y (fromStream ys))
345 (toStream z)
346 (toStream xs)
348-- | Right fold to a transformer monad. This is the most general right fold
349-- function. 'foldrS' is a special case of 'foldrT', however 'foldrS'
350-- implementation can be more efficient:
351--
352-- > foldrS = foldrT
353-- > foldrM f z s = runIdentityT $ foldrT (\x xs -> lift $ f x (runIdentityT xs)) (lift z) s
354--
355-- 'foldrT' can be used to translate streamly streams to other transformer
356-- monads e.g. to a different streaming type.
357--
358-- /Pre-release/
359{-# INLINE foldrT #-}
360foldrT :: (IsStream t, Monad m, Monad (s m), MonadTrans s)
361 => (a -> s m b -> s m b) -> s m b -> t m a -> s m b
362foldrT f z s = S.foldrT f z (toStreamS s)
364------------------------------------------------------------------------------
365-- Transformation by Mapping
366------------------------------------------------------------------------------
368-- |
369-- @
370-- mapM f = sequence . map f
371-- @
372--
373-- Apply a monadic function to each element of the stream and replace it with
374-- the output of the resulting action.
375--
376-- @
377-- >>> drain $ Stream.mapM putStr $ Stream.fromList ["a", "b", "c"]
378-- abc
379--
380-- >>> :{
381-- drain $ Stream.replicateM 10 (return 1)
382-- & (fromSerial . Stream.mapM (\x -> threadDelay 1000000 >> print x))
383-- :}
384-- 1
385-- ...
386-- 1
387--
388-- > drain $ Stream.replicateM 10 (return 1)
389-- & (fromAsync . Stream.mapM (\x -> threadDelay 1000000 >> print x))
390-- @
391--
392-- /Concurrent (do not use with 'fromParallel' on infinite streams)/
393--
394-- @since 0.1.0
395{-# INLINE_EARLY mapM #-}
396mapM :: forall t m a b. (IsStream t, MonadAsync m) =>
397 (a -> m b) -> t m a -> t m b
398mapM f = fromStream . K.mapMWith (toConsK (consM @t)) f . toStream
400{-# RULES "mapM serial" mapM = mapMSerial #-}
401{-# INLINE mapMSerial #-}
402mapMSerial :: Monad m => (a -> m b) -> SerialT m a -> SerialT m b
403mapMSerial = Serial.mapM
405-- |
406-- @
407-- sequence = mapM id
408-- @
409--
410-- Replace the elements of a stream of monadic actions with the outputs of
411-- those actions.
412--
413-- @
414-- >>> drain $ Stream.sequence $ Stream.fromList [putStr "a", putStr "b", putStrLn "c"]
415-- abc
416--
417-- >>> :{
418-- drain $ Stream.replicateM 3 (return $ threadDelay 1000000 >> print 1)
419-- & (fromSerial . Stream.sequence)
420-- :}
421-- 1
422-- 1
423-- 1
424--
425-- >>> :{
426-- drain $ Stream.replicateM 3 (return $ threadDelay 1000000 >> print 1)
427-- & (fromAsync . Stream.sequence)
428-- :}
429-- 1
430-- 1
431-- 1
432--
433-- @
434--
435-- /Concurrent (do not use with 'fromParallel' on infinite streams)/
436--
437-- @since 0.1.0
438{-# INLINE sequence #-}
439sequence :: (IsStream t, MonadAsync m) => t m (m a) -> t m a
440sequence = mapM id
442------------------------------------------------------------------------------
443-- Mapping side effects
444------------------------------------------------------------------------------
446-- | Tap the data flowing through a stream into a 'Fold'. For example, you may
447-- add a tap to log the contents flowing through the stream. The fold is used
448-- only for effects, its result is discarded.
449--
450-- @
451-- Fold m a b
452-- |
453-- -----stream m a ---------------stream m a-----
454--
455-- @
456--
457-- >>> Stream.drain $ Stream.tap (Fold.drainBy print) (Stream.enumerateFromTo 1 2)
458-- 1
459-- 2
460--
461-- Compare with 'trace'.
462--
463-- @since 0.7.0
464{-# INLINE tap #-}
465tap :: (IsStream t, Monad m) => FL.Fold m a b -> t m a -> t m a
466tap f xs = fromStreamD $ D.tap f (toStreamD xs)
468-- XXX Remove this. It can be expressed in terms of Fold.sampleFromThen.
469--
470-- | @tapOffsetEvery offset n@ taps every @n@th element in the stream
471-- starting at @offset@. @offset@ can be between @0@ and @n - 1@. Offset 0
472-- means start at the first element in the stream. If the offset is outside
473-- this range then @offset `mod` n@ is used as offset.
474--
475-- >>> Stream.drain $ Stream.tapOffsetEvery 0 2 (Fold.rmapM print Fold.toList) $ Stream.enumerateFromTo 0 10
476-- [0,2,4,6,8,10]
478--
479-- /Pre-release/
480--
481{-# INLINE tapOffsetEvery #-}
482tapOffsetEvery :: (IsStream t, Monad m)
483 => Int -> Int -> FL.Fold m a b -> t m a -> t m a
484tapOffsetEvery offset n f xs =
485 fromStreamD $ D.tapOffsetEvery offset n f (toStreamD xs)
487-- | Redirect a copy of the stream to a supplied fold and run it concurrently
488-- in an independent thread. The fold may buffer some elements. The buffer size
489-- is determined by the prevailing 'maxBuffer' setting.
490--
491-- @
492-- Stream m a -> m b
493-- |
494-- -----stream m a ---------------stream m a-----
495--
496-- @
497--
498-- @
499-- >>> Stream.drain $ Stream.tapAsync (Fold.drainBy print) (Stream.enumerateFromTo 1 2)
500-- 1
501-- 2
502--
503-- @
504--
505-- Exceptions from the concurrently running fold are propagated to the current
506-- computation. Note that, because of buffering in the fold, exceptions may be
507-- delayed and may not correspond to the current element being processed in the
508-- parent stream, but we guarantee that before the parent stream stops the tap
509-- finishes and all exceptions from it are drained.
510--
511-- >>> tapAsync f = Stream.tapAsyncK (Stream.fold f . Stream.adapt)
512--
513-- Compare with 'tap'.
514--
515-- /Pre-release/
516{-# INLINE tapAsync #-}
517tapAsync :: (IsStream t, MonadAsync m) => FL.Fold m a b -> t m a -> t m a
518tapAsync f xs = fromStreamD $ Par.tapAsyncF f (toStreamD xs)
520-- XXX We should keep only tapAsyncK as tapAsync can be implemented in terms
521-- of tapAsyncK and it has better performance. Rename this to tapAsync.
523-- | Like 'tapAsyncF' but uses a stream fold function instead of a 'Fold' type.
524--
525-- /Pre-release/
526{-# INLINE tapAsyncK #-}
527tapAsyncK :: (IsStream t, MonadAsync m) => (t m a -> m b) -> t m a -> t m a
528tapAsyncK f m = fromStream $ Par.tapAsyncK (f . fromStream) (toStream m)
530-- XXX rename this to tapManyAsync_?
531--
532-- | Concurrently distribute a stream to a collection of fold functions,
533-- discarding the outputs of the folds.
534--
535-- @
536-- > Stream.drain $ Stream.distributeAsync_ [Stream.mapM_ print, Stream.mapM_ print] (Stream.enumerateFromTo 1 2)
537-- 1
538-- 2
539-- 1
540-- 2
541--
542-- @
543--
544-- @
545-- distributeAsync_ = flip (foldr tapAsync)
546-- @
547--
548-- /Pre-release/
549--
550{-# INLINE distributeAsync_ #-}
551distributeAsync_ :: (Foldable f, IsStream t, MonadAsync m)
552 => f (t m a -> m b) -> t m a -> t m a
553distributeAsync_ = flip (Prelude.foldr tapAsyncK)
555-- | @pollCounts predicate transform fold stream@ counts those elements in the
556-- stream that pass the @predicate@. The resulting count stream is sent to
557-- another thread which transforms it using @transform@ and then folds it using
558-- @fold@. The thread is automatically cleaned up if the stream stops or
559-- aborts due to exception.
560--
561-- For example, to print the count of elements processed every second:
562--
563-- @
564-- > Stream.drain $ Stream.pollCounts (const True) (Stream.rollingMap (-) . Stream.delayPost 1) (FLold.drainBy print)
565-- $ Stream.enumerateFrom 0
566-- @
567--
568-- Note: This may not work correctly on 32-bit machines.
569--
570-- /Pre-release/
571--
572{-# INLINE pollCounts #-}
573pollCounts ::
574 (IsStream t, MonadAsync m)
575 => (a -> Bool)
576 -> (t m Int -> m b)
577 -> t m a
578 -> t m a
579pollCounts predicate f xs =
580 fromStreamD
581 $ D.pollCounts predicate (f . fromStreamD)
582 $ toStreamD xs
584-- | Apply a monadic function to each element flowing through the stream and
585-- discard the results.
586--
587-- >>> Stream.drain $ Stream.trace print (Stream.enumerateFromTo 1 2)
588-- 1
589-- 2
590--
591-- Compare with 'tap'.
592--
593-- @since 0.7.0
594{-# INLINE trace #-}
595trace :: (IsStream t, MonadAsync m) => (a -> m b) -> t m a -> t m a
596trace f = mapM (\x -> void (f x) >> return x)
598-- | Perform a side effect before yielding each element of the stream and
599-- discard the results.
600--
601-- @
602-- >>> Stream.drain $ Stream.trace_ (print "got here") (Stream.enumerateFromTo 1 2)
603-- "got here"
604-- "got here"
605--
606-- @
607--
608-- Same as 'interspersePrefix_' but always serial.
609--
610-- See also: 'trace'
611--
612-- /Pre-release/
613{-# INLINE trace_ #-}
614trace_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
615trace_ eff = fromStreamD . D.mapM (\x -> eff >> return x) . toStreamD
617------------------------------------------------------------------------------
618-- Scanning with a Fold
619------------------------------------------------------------------------------
621-- | Scan a stream using the given monadic fold.
622--
623-- >>> Stream.toList $ Stream.takeWhile (< 10) $ Stream.scan Fold.sum (Stream.fromList [1..10])
624-- [0,1,3,6]
625--
626-- @since 0.7.0
627{-# INLINE scan #-}
628scan :: (IsStream t, Monad m) => Fold m a b -> t m a -> t m b
629scan fld m = fromStreamD $ D.scanOnce fld $ toStreamD m
631-- | Like 'scan' but restarts scanning afresh when the scanning fold
632-- terminates.
633--
634-- /Pre-release/
635{-# INLINE scanMany #-}
636scanMany :: (IsStream t, Monad m) => Fold m a b -> t m a -> t m b
637scanMany fld m = fromStreamD $ D.scanMany fld $ toStreamD m
639-- | Postscan a stream using the given monadic fold.
640--
641-- The following example extracts the input stream up to a point where the
642-- running average of elements is no more than 10:
643--
644-- >>> import Data.Maybe (fromJust)
645-- >>> let avg = Fold.teeWith (/) Fold.sum (fmap fromIntegral Fold.length)
646-- >>> :{
647-- Stream.toList
648-- $ Stream.map (fromJust . fst)
649-- $ Stream.takeWhile (\(_,x) -> x <= 10)
650-- $ Stream.postscan (Fold.tee Fold.last avg) (Stream.enumerateFromTo 1.0 100.0)
651-- :}
652-- [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]
653--
654-- @since 0.7.0
655{-# INLINE postscan #-}
656postscan :: (IsStream t, Monad m) => Fold m a b -> t m a -> t m b
657postscan fld = fromStreamD . D.postscanOnce fld . toStreamD
659------------------------------------------------------------------------------
660-- Scanning - Transformation by Folding
661------------------------------------------------------------------------------
663-- XXX It may be useful to have a version of scan where we can keep the
664-- accumulator independent of the value emitted. So that we do not necessarily
665-- have to keep a value in the accumulator which we are not using. We can pass
666-- an extraction function that will take the accumulator and the current value
667-- of the element and emit the next value in the stream. That will also make it
668-- possible to modify the accumulator after using it. In fact, the step function
669-- can return new accumulator and the value to be emitted. The signature would
670-- be more like mapAccumL. Or we can change the signature of scanx to
671-- accommodate this.
672--
673-- | Strict left scan with an extraction function. Like 'scanl'', but applies a
674-- user supplied extraction function (the third argument) at each step. This is
675-- designed to work with the @foldl@ library. The suffix @x@ is a mnemonic for
676-- extraction.
677--
678-- /Since 0.2.0/
679--
680-- /Since: 0.7.0 (Monad m constraint)/
681{-# DEPRECATED scanx "Please use scanl followed by map instead." #-}
682{-# INLINE scanx #-}
683scanx :: (IsStream t, Monad m) => (x -> a -> x) -> x -> (x -> b) -> t m a -> t m b
684scanx step begin done = fromStreamS . S.scanlx' step begin done . toStreamS
686-- XXX this needs to be concurrent
687-- XXX because of the use of D.cons for appending, scanlM' has quadratic
688-- complexity when iterated over a stream. We should use StreamK style scanlM'
689-- for linear performance on iteration.
690--
691-- | Like 'scanl'' but with a monadic step function and a monadic seed.
692--
693-- /Since: 0.4.0/
694--
695-- /Since: 0.8.0 (signature change)/
696{-# INLINE scanlM' #-}
697scanlM' :: (IsStream t, Monad m) => (b -> a -> m b) -> m b -> t m a -> t m b
698scanlM' step begin m = fromStreamD $ D.scanlM' step begin $ toStreamD m
700-- XXX because of the use of D.cons for appending, scanl' has quadratic
701-- complexity when iterated over a stream. We should use StreamK style scanlM'
702-- for linear performance on iteration.
704-- | Strict left scan. Like 'map', 'scanl'' too is a one to one transformation,
705-- however it adds an extra element.
706--
707-- @
708-- >>> Stream.toList $ Stream.scanl' (+) 0 $ fromList [1,2,3,4]
709-- [0,1,3,6,10]
710--
711-- @
712--
713-- @
714-- >>> Stream.toList $ Stream.scanl' (flip (:)) [] $ Stream.fromList [1,2,3,4]
715-- [[],[1],[2,1],[3,2,1],[4,3,2,1]]
716--
717-- @
718--
719-- The output of 'scanl'' is the initial value of the accumulator followed by
720-- all the intermediate steps and the final result of 'foldl''.
721--
722-- By streaming the accumulated state after each fold step, we can share the
723-- state across multiple stages of stream composition. Each stage can modify or
724-- extend the state, do some processing with it and emit it for the next stage,
725-- thus modularizing the stream processing. This can be useful in
726-- stateful or event-driven programming.
727--
728-- Consider the following monolithic example, computing the sum and the product
729-- of the elements in a stream in one go using a @foldl'@:
730--
731-- @
732-- >>> Stream.foldl' (\(s, p) x -> (s + x, p * x)) (0,1) $ Stream.fromList [1,2,3,4]
733-- (10,24)
734--
735-- @
736--
737-- Using @scanl'@ we can make it modular by computing the sum in the first
738-- stage and passing it down to the next stage for computing the product:
739--
740-- @
741-- >>> :{
742-- Stream.foldl' (\(_, p) (s, x) -> (s, p * x)) (0,1)
743-- $ Stream.scanl' (\(s, _) x -> (s + x, x)) (0,1)
744-- $ Stream.fromList [1,2,3,4]
745-- :}
746-- (10,24)
747--
748-- @
749--
750-- IMPORTANT: 'scanl'' evaluates the accumulator to WHNF. To avoid building
751-- lazy expressions inside the accumulator, it is recommended that a strict
752-- data structure is used for accumulator.
753--
754-- >>> scanl' step z = scan (Fold.foldl' step z)
755-- >>> scanl' f z xs = scanlM' (\a b -> return (f a b)) (return z) xs
756-- >>> scanl' f z xs = z `Stream.cons` postscanl' f z xs
757--
758-- See also: 'usingStateT'
759--
760-- @since 0.2.0
761{-# INLINE scanl' #-}
762scanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
763scanl' step z m = fromStreamS $ S.scanl' step z $ toStreamS m
765-- | Like 'scanl'' but does not stream the initial value of the accumulator.
766--
767-- >>> postscanl' step z = postscan (Fold.foldl' step z)
768-- >>> postscanl' f z = postscanlM' (\a b -> return (f a b)) (return z)
769-- >>> postscanl' f z xs = Stream.drop 1 $ Stream.scanl' f z xs
770--
771-- @since 0.7.0
772{-# INLINE postscanl' #-}
773postscanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
774postscanl' step z m = fromStreamD $ D.postscanl' step z $ toStreamD m
776-- XXX prescanl does not sound very useful, enable only if there is a
777-- compelling use case.
778--
779-- | Like scanl' but does not stream the final value of the accumulator.
780--
781-- /Pre-release/
782{-# INLINE prescanl' #-}
783prescanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
784prescanl' step z m = fromStreamD $ D.prescanl' step z $ toStreamD m
786-- XXX this needs to be concurrent
787-- | Like prescanl' but with a monadic step function and a monadic seed.
788--
789-- /Pre-release/
790{-# INLINE prescanlM' #-}
791prescanlM' :: (IsStream t, Monad m) => (b -> a -> m b) -> m b -> t m a -> t m b
792prescanlM' step z m = fromStreamD $ D.prescanlM' step z $ toStreamD m
794-- XXX this needs to be concurrent
795-- | Like 'scanl1'' but with a monadic step function.
796--
797-- @since 0.6.0
798{-# INLINE scanl1M' #-}
799scanl1M' :: (IsStream t, Monad m) => (a -> a -> m a) -> t m a -> t m a
800scanl1M' step m = fromStreamD $ D.scanl1M' step $ toStreamD m
802-- | Like 'scanl'' but for a non-empty stream. The first element of the stream
803-- is used as the initial value of the accumulator. Does nothing if the stream
804-- is empty.
805--
806-- @
807-- >>> Stream.toList $ Stream.scanl1' (+) $ fromList [1,2,3,4]
808-- [1,3,6,10]
809--
810-- @
811--
812-- @since 0.6.0
813{-# INLINE scanl1' #-}
814scanl1' :: (IsStream t, Monad m) => (a -> a -> a) -> t m a -> t m a
815scanl1' step m = fromStreamD $ D.scanl1' step $ toStreamD m
817------------------------------------------------------------------------------
818-- Filtering
819------------------------------------------------------------------------------
821-- | Modify a @t m a -> t m a@ stream transformation that accepts a predicate
822-- @(a -> b)@ to accept @((s, a) -> b)@ instead, provided a transformation @t m
823-- a -> t m (s, a)@. Convenient to filter with index or time.
824--
825-- @
826-- filterWithIndex = with indexed filter
827-- filterWithAbsTime = with timestamped filter
828-- filterWithRelTime = with timeIndexed filter
829-- @
830--
831-- /Pre-release/
832{-# INLINE with #-}
833with :: forall (t :: (Type -> Type) -> Type -> Type) m a b s. Functor (t m) =>
834 (t m a -> t m (s, a))
835 -> (((s, a) -> b) -> t m (s, a) -> t m (s, a))
836 -> (((s, a) -> b) -> t m a -> t m a)
837with f comb g = fmap snd . comb g . f
839-- | Include only those elements that pass a predicate.
840--
841-- @since 0.1.0
842{-# INLINE filter #-}
843filter :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m a
844filter p m = fromStreamS $ S.filter p $ toStreamS m
846-- | Same as 'filter' but with a monadic predicate.
847--
848-- @since 0.4.0
849{-# INLINE filterM #-}
850filterM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
851filterM p m = fromStreamD $ D.filterM p $ toStreamD m
853-- | Drop repeated elements that are adjacent to each other using the supplied
854-- comparison function.
855--
856-- @uniq = uniqBy (==)
857--
858-- To strip duplicate path separators:
859--
860-- @
861-- f x y = x == '/' && x == y
862-- Stream.toList $ Stream.uniqBy f $ Stream.fromList "//a//b"
863-- "/a/b"
864-- @
865--
866-- Space: @O(1)@
867--
868-- See also: 'nubBy'.
869--
870-- /Pre-release/
871--
872{-# INLINE uniqBy #-}
873uniqBy :: (IsStream t, Monad m, Functor (t m)) =>
874 (a -> a -> Bool) -> t m a -> t m a
875uniqBy eq = catMaybes . rollingMap f
877 where
879 f pre curr =
880 case pre of
881 Nothing -> Just curr
882 Just x -> if x `eq` curr then Nothing else Just curr
884-- | Drop repeated elements that are adjacent to each other.
885--
886-- @since 0.6.0
887{-# INLINE uniq #-}
888uniq :: (Eq a, IsStream t, Monad m) => t m a -> t m a
889uniq = fromStreamD . D.uniq . toStreamD
891-- | Strip all leading and trailing occurrences of an element passing a
892-- predicate and make all other consecutive occurrences uniq.
893--
894-- @
895-- prune p = dropWhileAround p $ uniqBy (x y -> p x && p y)
896-- @
897--
898-- @
899-- > Stream.prune isSpace (Stream.fromList " hello world! ")
900-- "hello world!"
901--
902-- @
903--
904-- Space: @O(1)@
905--
906-- /Unimplemented/
907{-# INLINE prune #-}
908prune ::
909 -- (IsStream t, Monad m, Eq a) =>
910 (a -> Bool) -> t m a -> t m a
911prune = error "Not implemented yet!"
913-- Possible implementation:
914-- @repeated =
915-- Stream.catMaybes . Stream.parseMany (Parser.groupBy (==) Fold.repeated)@
916--
917-- 'Fold.repeated' should return 'Just' when repeated, and 'Nothing' for a
918-- single element.
919--
920-- | Emit only repeated elements, once.
921--
922-- /Unimplemented/
923repeated :: -- (IsStream t, Monad m, Eq a) =>
924 t m a -> t m a
925repeated = undefined
927-- We can have more efficient implementations for nubOrd and nubInt by using
928-- Set and IntSet to find/remove duplication. For Hashable we can use a
929-- hashmap. Use rewrite rules to specialize to more efficient impls.
930--
931-- | Drop repeated elements anywhere in the stream.
932--
933-- /Caution: not scalable for infinite streams/
934--
935-- /See also: nubWindowBy/
936--
937-- /Unimplemented/
938--
939{-# INLINE nubBy #-}
940nubBy :: -- (IsStream t, Monad m) =>
941 (a -> a -> Bool) -> t m a -> t m a
942nubBy = undefined -- fromStreamD . D.nubBy . toStreamD
944-- | Deletes the first occurrence of the element in the stream that satisfies
945-- the given equality predicate.
946--
947-- @
948-- >>> Stream.toList $ Stream.deleteBy (==) 3 $ Stream.fromList [1,3,3,5]
949-- [1,3,5]
950--
951-- @
952--
953-- @since 0.6.0
954{-# INLINE deleteBy #-}
955deleteBy :: (IsStream t, Monad m) => (a -> a -> Bool) -> a -> t m a -> t m a
956deleteBy cmp x m = fromStreamS $ S.deleteBy cmp x (toStreamS m)
958------------------------------------------------------------------------------
959-- Lossy Buffering
960------------------------------------------------------------------------------
962-- XXX We could use 'maxBuffer Block/Drop/Rotate/Sample' instead. However we
963-- may want to have the evaluation rate independent of the sampling rate. To
964-- support that we can decouple evaluation and sampling in independent stages.
965-- The sampling stage would strictly evaluate and sample, the evaluation stage
966-- would control the evaluation rate.
968-- | Evaluate the input stream continuously and keep only the oldest @n@
969-- elements in the buffer, discard the new ones when the buffer is full. When
970-- the output stream is evaluated it consumes the values from the buffer in a
971-- FIFO manner.
972--
973-- /Unimplemented/
974--
975{-# INLINE sampleOld #-}
976sampleOld :: -- (IsStream t, Monad m) =>
977 Int -> t m a -> t m a
978sampleOld = undefined
980-- | Evaluate the input stream continuously and keep only the latest @n@
981-- elements in a ring buffer, keep discarding the older ones to make space for
982-- the new ones. When the output stream is evaluated it consumes the values
983-- from the buffer in a FIFO manner.
984--
985-- /Unimplemented/
986--
987{-# INLINE sampleNew #-}
988sampleNew :: -- (IsStream t, Monad m) =>
989 Int -> t m a -> t m a
990sampleNew = undefined
992-- | Like 'sampleNew' but samples at uniform intervals to match the consumer
993-- rate. Note that 'sampleNew' leads to non-uniform sampling depending on the
994-- consumer pattern.
995--
996-- /Unimplemented/
997--
998{-# INLINE sampleRate #-}
999sampleRate :: -- (IsStream t, Monad m) =>
1000 Double -> t m a -> t m a
1001sampleRate = undefined
1003------------------------------------------------------------------------------
1004-- Trimming
1005------------------------------------------------------------------------------
1007-- | Same as 'takeWhile' but with a monadic predicate.
1009-- @since 0.4.0
1010{-# INLINE takeWhileM #-}
1011takeWhileM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
1012takeWhileM p m = fromStreamD $ D.takeWhileM p $ toStreamD m
1014-- See the lastN fold for impl hints. Use a Data.Array based ring buffer.
1016-- takeLast n = Stream.concatM . fmap Array.toStream . fold Fold.lastN
1018-- | Take @n@ elements at the end of the stream.
1020-- O(n) space, where n is the number elements taken.
1022-- /Unimplemented/
1023{-# INLINE takeLast #-}
1024takeLast :: -- (IsStream t, Monad m) =>
1025 Int -> t m a -> t m a
1026takeLast = undefined -- fromStreamD $ D.takeLast n $ toStreamD m
1028-- | Take time interval @i@ seconds at the end of the stream.
1030-- O(n) space, where n is the number elements taken.
1032-- /Unimplemented/
1033{-# INLINE takeLastInterval #-}
1034takeLastInterval :: -- (IsStream t, Monad m) =>
1035 Double -> t m a -> t m a
1036takeLastInterval = undefined -- fromStreamD $ D.takeLast n $ toStreamD m
1038-- | Take all consecutive elements at the end of the stream for which the
1039-- predicate is true.
1041-- O(n) space, where n is the number elements taken.
1043-- /Unimplemented/
1044{-# INLINE takeWhileLast #-}
1045takeWhileLast :: -- (IsStream t, Monad m) =>
1046 (a -> Bool) -> t m a -> t m a
1047takeWhileLast = undefined -- fromStreamD $ D.takeWhileLast n $ toStreamD m
1049-- | Like 'takeWhile' and 'takeWhileLast' combined.
1051-- O(n) space, where n is the number elements taken from the end.
1053-- /Unimplemented/
1054{-# INLINE takeWhileAround #-}
1055takeWhileAround :: -- (IsStream t, Monad m) =>
1056 (a -> Bool) -> t m a -> t m a
1057takeWhileAround = undefined -- fromStreamD $ D.takeWhileAround n $ toStreamD m
1059-- | @takeInterval duration@ yields stream elements upto specified time
1060-- @duration@. The duration starts when the stream is evaluated for the first
1061-- time, before the first element is yielded. The time duration is checked
1062-- before generating each element, if the duration has expired the stream
1063-- stops.
1065-- The total time taken in executing the stream is guaranteed to be /at least/
1066-- @duration@, however, because the duration is checked before generating an
1067-- element, the upper bound is indeterminate and depends on the time taken in
1068-- generating and processing the last element.
1070-- No element is yielded if the duration is zero. At least one element is
1071-- yielded if the duration is non-zero.
1073-- /Pre-release/
1075{-# INLINE takeInterval #-}
1076takeInterval ::(MonadIO m, IsStream t, TimeUnit64 d) => d -> t m a -> t m a
1077takeInterval d = fromStreamD . D.takeByTime d . toStreamD
1079-- | Drop elements in the stream as long as the predicate succeeds and then
1080-- take the rest of the stream.
1082-- @since 0.1.0
1083{-# INLINE dropWhile #-}
1084dropWhile :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m a
1085dropWhile p m = fromStreamS $ S.dropWhile p $ toStreamS m
1087-- | Same as 'dropWhile' but with a monadic predicate.
1089-- @since 0.4.0
1090{-# INLINE dropWhileM #-}
1091dropWhileM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
1092dropWhileM p m = fromStreamD $ D.dropWhileM p $ toStreamD m
1094-- | @dropInterval duration@ drops stream elements until specified @duration@ has
1095-- passed. The duration begins when the stream is evaluated for the first
1096-- time. The time duration is checked /after/ generating a stream element, the
1097-- element is yielded if the duration has expired otherwise it is dropped.
1099-- The time elapsed before starting to generate the first element is /at most/
1100-- @duration@, however, because the duration expiry is checked after the
1101-- element is generated, the lower bound is indeterminate and depends on the
1102-- time taken in generating an element.
1104-- All elements are yielded if the duration is zero.
1106-- /Pre-release/
1108{-# INLINE dropInterval #-}
1109dropInterval ::(MonadIO m, IsStream t, TimeUnit64 d) => d -> t m a -> t m a
1110dropInterval d = fromStreamD . D.dropByTime d . toStreamD
1112-- | Drop @n@ elements at the end of the stream.
1114-- O(n) space, where n is the number elements dropped.
1116-- /Unimplemented/
1117{-# INLINE dropLast #-}
1118dropLast :: -- (IsStream t, Monad m) =>
1119 Int -> t m a -> t m a
1120dropLast = undefined -- fromStreamD $ D.dropLast n $ toStreamD m
1122-- | Drop time interval @i@ seconds at the end of the stream.
1124-- O(n) space, where n is the number elements dropped.
1126-- /Unimplemented/
1127{-# INLINE dropLastInterval #-}
1128dropLastInterval :: -- (IsStream t, Monad m) =>
1129 Int -> t m a -> t m a
1130dropLastInterval = undefined
1132-- | Drop all consecutive elements at the end of the stream for which the
1133-- predicate is true.
1135-- O(n) space, where n is the number elements dropped.
1137-- /Unimplemented/
1138{-# INLINE dropWhileLast #-}
1139dropWhileLast :: -- (IsStream t, Monad m) =>
1140 (a -> Bool) -> t m a -> t m a
1141dropWhileLast = undefined -- fromStreamD $ D.dropWhileLast n $ toStreamD m
1143-- | Like 'dropWhile' and 'dropWhileLast' combined.
1145-- O(n) space, where n is the number elements dropped from the end.
1147-- /Unimplemented/
1148{-# INLINE dropWhileAround #-}
1149dropWhileAround :: -- (IsStream t, Monad m) =>
1150 (a -> Bool) -> t m a -> t m a
1151dropWhileAround = undefined -- fromStreamD $ D.dropWhileAround n $ toStreamD m
1153------------------------------------------------------------------------------
1154-- Inserting Elements
1155------------------------------------------------------------------------------
1157-- | @insertBy cmp elem stream@ inserts @elem@ before the first element in
1158-- @stream@ that is less than @elem@ when compared using @cmp@.
1160-- @
1161-- insertBy cmp x = 'mergeBy' cmp ('fromPure' x)
1162-- @
1164-- @
1165-- >>> Stream.toList $ Stream.insertBy compare 2 $ Stream.fromList [1,3,5]
1166-- [1,2,3,5]
1168-- @
1170-- @since 0.6.0
1171{-# INLINE insertBy #-}
1172insertBy ::
1173 (IsStream t, Monad m) => (a -> a -> Ordering) -> a -> t m a -> t m a
1174insertBy cmp x m = fromStreamS $ S.insertBy cmp x (toStreamS m)
1176-- | Insert a pure value between successive elements of a stream.
1178-- >>> Stream.toList $ Stream.intersperse ',' $ Stream.fromList "hello"
1179-- "h,e,l,l,o"
1181-- @since 0.7.0
1182{-# INLINE intersperse #-}
1183intersperse :: (IsStream t, MonadAsync m) => a -> t m a -> t m a
1184intersperse a = fromStreamS . S.intersperse a . toStreamS
1186-- | Insert a side effect before consuming an element of a stream except the
1187-- first one.
1189-- >>> Stream.drain $ Stream.trace putChar $ Stream.intersperseM_ (putChar '.') $ Stream.fromList "hello"
1190-- h.e.l.l.o
1192-- /Pre-release/
1193{-# INLINE intersperseM_ #-}
1194intersperseM_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
1195intersperseM_ m = fromStreamD . D.intersperseM_ m . toStreamD
1197-- | Intersperse a monadic action into the input stream after every @n@
1198-- elements.
1200-- @
1201-- > Stream.toList $ Stream.intersperseBySpan 2 (return ',') $ Stream.fromList "hello"
1202-- "he,ll,o"
1204-- @
1206-- /Unimplemented/
1207{-# INLINE intersperseBySpan #-}
1208intersperseBySpan :: -- IsStream t =>
1209 Int -> m a -> t m a -> t m a
1210intersperseBySpan _n _f _xs = undefined
1212-- | Insert an effect and its output after consuming an element of a stream.
1214-- >>> Stream.toList $ Stream.trace putChar $ intersperseSuffix (putChar '.' >> return ',') $ Stream.fromList "hello"
1215-- h.,e.,l.,l.,o.,"h,e,l,l,o,"
1217-- /Pre-release/
1218{-# INLINE intersperseSuffix #-}
1219intersperseSuffix :: (IsStream t, Monad m) => m a -> t m a -> t m a
1220intersperseSuffix m = fromStreamD . D.intersperseSuffix m . toStreamD
1222-- | Insert a side effect after consuming an element of a stream.
1224-- @
1225-- >>> Stream.mapM_ putChar $ Stream.intersperseSuffix_ (threadDelay 1000000) $ Stream.fromList "hello"
1226-- hello
1228-- @
1230-- /Pre-release/
1232{-# INLINE intersperseSuffix_ #-}
1233intersperseSuffix_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
1234intersperseSuffix_ m = fromStreamD . D.intersperseSuffix_ m . toStreamD
1236-- XXX Use an offset argument, like tapOffsetEvery
1238-- | Like 'intersperseSuffix' but intersperses an effectful action into the
1239-- input stream after every @n@ elements and after the last element.
1241-- >>> Stream.toList $ Stream.intersperseSuffixBySpan 2 (return ',') $ Stream.fromList "hello"
1242-- "he,ll,o,"
1244-- /Pre-release/
1246{-# INLINE intersperseSuffixBySpan #-}
1247intersperseSuffixBySpan :: (IsStream t, Monad m)
1248 => Int -> m a -> t m a -> t m a
1249intersperseSuffixBySpan n eff =
1250 fromStreamD . D.intersperseSuffixBySpan n eff . toStreamD
1252-- | Insert a side effect before consuming an element of a stream.
1254-- >>> Stream.toList $ Stream.trace putChar $ Stream.interspersePrefix_ (putChar '.' >> return ',') $ Stream.fromList "hello"
1255-- .h.e.l.l.o"hello"
1257-- Same as 'trace_' but may be concurrent.
1259-- /Concurrent/
1261-- /Pre-release/
1263{-# INLINE interspersePrefix_ #-}
1264interspersePrefix_ :: (IsStream t, MonadAsync m) => m b -> t m a -> t m a
1265interspersePrefix_ m = mapM (\x -> void m >> return x)
1267------------------------------------------------------------------------------
1268-- Inserting Time
1269------------------------------------------------------------------------------
1271-- Note: delay must be serial.
1273-- | Introduce a delay of specified seconds before consuming an element of the
1274-- stream except the first one.
1276-- >>> Stream.mapM_ print $ Stream.timestamped $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
1277-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),1)
1278-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),2)
1279-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),3)
1281-- @since 0.8.0
1283{-# INLINE delay #-}
1284delay :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
1285delay n = intersperseM_ $ liftIO $ threadDelay $ round $ n * 1000000
1287-- Note: delay must be serial.
1289-- | Introduce a delay of specified seconds after consuming an element of a
1290-- stream.
1292-- >>> Stream.mapM_ print $ Stream.timestamped $ Stream.delayPost 1 $ Stream.enumerateFromTo 1 3
1293-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),1)
1294-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),2)
1295-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),3)
1297-- /Pre-release/
1299{-# INLINE delayPost #-}
1300delayPost :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
1301delayPost n = intersperseSuffix_ $ liftIO $ threadDelay $ round $ n * 1000000
1303-- Note: delay must be serial, that's why 'trace_' is used.
1305-- | Introduce a delay of specified seconds before consuming an element of a
1306-- stream.
1308-- >>> Stream.mapM_ print $ Stream.timestamped $ Stream.delayPre 1 $ Stream.enumerateFromTo 1 3
1309-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),1)
1310-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),2)
1311-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),3)
1313-- /Pre-release/
1315{-# INLINE delayPre #-}
1316delayPre :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
1317delayPre n = trace_ $ liftIO $ threadDelay $ round $ n * 1000000
1319------------------------------------------------------------------------------
1320-- Reorder in sequence
1321------------------------------------------------------------------------------
1323-- | Buffer until the next element in sequence arrives. The function argument
1324-- determines the difference in sequence numbers. This could be useful in
1325-- implementing sequenced streams, for example, TCP reassembly.
1327-- /Unimplemented/
1329{-# INLINE reassembleBy #-}
1330reassembleBy
1331 :: -- (IsStream t, Monad m) =>
1332 Fold m a b
1333 -> (a -> a -> Int)
1334 -> t m a
1335 -> t m b
1336reassembleBy = undefined
1338------------------------------------------------------------------------------
1339-- Position Indexing
1340------------------------------------------------------------------------------
1342-- |
1343-- > indexed = Stream.postscanl' (\(i, _) x -> (i + 1, x)) (-1,undefined)
1344-- > indexed = Stream.zipWith (,) (Stream.enumerateFrom 0)
1346-- Pair each element in a stream with its index, starting from index 0.
1348-- >>> Stream.toList $ Stream.indexed $ Stream.fromList "hello"
1349-- [(0,'h'),(1,'e'),(2,'l'),(3,'l'),(4,'o')]
1351-- @since 0.6.0
1352{-# INLINE indexed #-}
1353indexed :: (IsStream t, Monad m) => t m a -> t m (Int, a)
1354indexed = fromStreamD . D.indexed . toStreamD
1356-- |
1357-- > indexedR n = Stream.postscanl' (\(i, _) x -> (i - 1, x)) (n + 1,undefined)
1358-- > indexedR n = Stream.zipWith (,) (Stream.enumerateFromThen n (n - 1))
1360-- Pair each element in a stream with its index, starting from the
1361-- given index @n@ and counting down.
1363-- >>> Stream.toList $ Stream.indexedR 10 $ Stream.fromList "hello"
1364-- [(10,'h'),(9,'e'),(8,'l'),(7,'l'),(6,'o')]
1366-- @since 0.6.0
1367{-# INLINE indexedR #-}
1368indexedR :: (IsStream t, Monad m) => Int -> t m a -> t m (Int, a)
1369indexedR n = fromStreamD . D.indexedR n . toStreamD
1371-------------------------------------------------------------------------------
1372-- Time Indexing
1373-------------------------------------------------------------------------------
1375-- Note: The timestamp stream must be the second stream in the zip so that the
1376-- timestamp is generated after generating the stream element and not before.
1377-- If we do not do that then the following example will generate the same
1378-- timestamp for first two elements:
1380-- Stream.mapM_ print $ Stream.timestamped $ Stream.delay $ Stream.enumerateFromTo 1 3
1382-- | Pair each element in a stream with an absolute timestamp, using a clock of
1383-- specified granularity. The timestamp is generated just before the element
1384-- is consumed.
1386-- >>> Stream.mapM_ print $ Stream.timestampWith 0.01 $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
1387-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),1)
1388-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),2)
1389-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),3)
1391-- /Pre-release/
1393{-# INLINE timestampWith #-}
1394timestampWith :: (IsStream t, MonadAsync m, Functor (t m))
1395 => Double -> t m a -> t m (AbsTime, a)
1396timestampWith g stream = zipWith (flip (,)) stream (absTimesWith g)
1398-- TBD: check performance vs a custom implementation without using zipWith.
1400-- /Pre-release/
1402{-# INLINE timestamped #-}
1403timestamped :: (IsStream t, MonadAsync m, Functor (t m))
1404 => t m a -> t m (AbsTime, a)
1405timestamped = timestampWith 0.01
1407-- | Pair each element in a stream with relative times starting from 0, using a
1408-- clock with the specified granularity. The time is measured just before the
1409-- element is consumed.
1411-- >>> Stream.mapM_ print $ Stream.timeIndexWith 0.01 $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
1412-- (RelTime64 (NanoSecond64 ...),1)
1413-- (RelTime64 (NanoSecond64 ...),2)
1414-- (RelTime64 (NanoSecond64 ...),3)
1416-- /Pre-release/
1418{-# INLINE timeIndexWith #-}
1419timeIndexWith :: (IsStream t, MonadAsync m, Functor (t m))
1420 => Double -> t m a -> t m (RelTime64, a)
1421timeIndexWith g stream = zipWith (flip (,)) stream (relTimesWith g)
1423-- | Pair each element in a stream with relative times starting from 0, using a
1424-- 10 ms granularity clock. The time is measured just before the element is
1425-- consumed.
1427-- >>> Stream.mapM_ print $ Stream.timeIndexed $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
1428-- (RelTime64 (NanoSecond64 ...),1)
1429-- (RelTime64 (NanoSecond64 ...),2)
1430-- (RelTime64 (NanoSecond64 ...),3)
1432-- /Pre-release/
1434{-# INLINE timeIndexed #-}
1435timeIndexed :: (IsStream t, MonadAsync m, Functor (t m))
1436 => t m a -> t m (RelTime64, a)
1437timeIndexed = timeIndexWith 0.01
1439------------------------------------------------------------------------------
1440-- Searching
1441------------------------------------------------------------------------------
1443-- | Find all the indices where the value of the element in the stream is equal
1444-- to the given value.
1446-- > elemIndices a = findIndices (== a)
1448-- @since 0.5.0
1449{-# INLINE elemIndices #-}
1450elemIndices :: (IsStream t, Eq a, Monad m) => a -> t m a -> t m Int
1451elemIndices a = findIndices (== a)
1453------------------------------------------------------------------------------
1454-- Rolling map
1455------------------------------------------------------------------------------
1457-- XXX this is not a one-to-one map so calling it map may not be right.
1458-- We can perhaps call it zipWithTail or rollWith.
1460-- | Apply a function on every two successive elements of a stream. The first
1461-- argument of the map function is the previous element and the second argument
1462-- is the current element. When the current element is the first element, the
1463-- previous element is 'Nothing'.
1465-- /Pre-release/
1467{-# INLINE rollingMap #-}
1468rollingMap :: (IsStream t, Monad m) => (Maybe a -> a -> b) -> t m a -> t m b
1469rollingMap f m = fromStreamD $ D.rollingMap f $ toStreamD m
1471-- | Like 'rollingMap' but with an effectful map function.
1473-- /Pre-release/
1475{-# INLINE rollingMapM #-}
1476rollingMapM :: (IsStream t, Monad m) => (Maybe a -> a -> m b) -> t m a -> t m b
1477rollingMapM f m = fromStreamD $ D.rollingMapM f $ toStreamD m
1479-- | Like 'rollingMap' but requires at least two elements in the stream,
1480-- returns an empty stream otherwise.
1482-- This is the stream equivalent of the list idiom @zipWith f xs (tail xs)@.
1484-- /Pre-release/
1486{-# INLINE rollingMap2 #-}
1487rollingMap2 :: (IsStream t, Monad m) => (a -> a -> b) -> t m a -> t m b
1488rollingMap2 f m = fromStreamD $ D.rollingMap2 f $ toStreamD m
1490------------------------------------------------------------------------------
1491-- Maybe Streams
1492------------------------------------------------------------------------------
1494-- | Map a 'Maybe' returning function to a stream, filter out the 'Nothing'
1495-- elements, and return a stream of values extracted from 'Just'.
1497-- Equivalent to:
1499-- @
1500-- mapMaybe f = Stream.map 'fromJust' . Stream.filter 'isJust' . Stream.map f
1501-- @
1503-- @since 0.3.0
1504{-# INLINE mapMaybe #-}
1505mapMaybe :: (IsStream t, Monad m) => (a -> Maybe b) -> t m a -> t m b
1506mapMaybe f m = fromStreamS $ S.mapMaybe f $ toStreamS m
1508-- | Like 'mapMaybe' but maps a monadic function.
1510-- Equivalent to:
1512-- @
1513-- mapMaybeM f = Stream.map 'fromJust' . Stream.filter 'isJust' . Stream.mapM f
1514-- @
1516-- /Concurrent (do not use with 'fromParallel' on infinite streams)/
1518-- @since 0.3.0
1519{-# INLINE_EARLY mapMaybeM #-}
1520mapMaybeM :: (IsStream t, MonadAsync m, Functor (t m))
1521 => (a -> m (Maybe b)) -> t m a -> t m b
1522mapMaybeM f = fmap fromJust . filter isJust . mapM f
1524{-# RULES "mapMaybeM serial" mapMaybeM = mapMaybeMSerial #-}
1525{-# INLINE mapMaybeMSerial #-}
1526mapMaybeMSerial :: Monad m => (a -> m (Maybe b)) -> SerialT m a -> SerialT m b
1527mapMaybeMSerial f m = fromStreamD $ D.mapMaybeM f $ toStreamD m
1529-- | In a stream of 'Maybe's, discard 'Nothing's and unwrap 'Just's.
1531-- /Pre-release/
1533{-# INLINE catMaybes #-}
1534catMaybes :: (IsStream t, Monad m, Functor (t m)) => t m (Maybe a) -> t m a
1535catMaybes = fmap fromJust . filter isJust
1537------------------------------------------------------------------------------
1538-- Either streams
1539------------------------------------------------------------------------------
1541-- | Discard 'Right's and unwrap 'Left's in an 'Either' stream.
1543-- /Pre-release/
1545{-# INLINE lefts #-}
1546lefts :: (IsStream t, Monad m, Functor (t m)) => t m (Either a b) -> t m a
1547lefts = fmap (fromLeft undefined) . filter isLeft
1549-- | Discard 'Left's and unwrap 'Right's in an 'Either' stream.
1551-- /Pre-release/
1553{-# INLINE rights #-}
1554rights :: (IsStream t, Monad m, Functor (t m)) => t m (Either a b) -> t m b
1555rights = fmap (fromRight undefined) . filter isRight
1557-- | Remove the either wrapper and flatten both lefts and as well as rights in
1558-- the output stream.
1560-- /Pre-release/
1562{-# INLINE both #-}
1563both :: Functor (t m) => t m (Either a a) -> t m a
1564both = fmap (either id id)
1566------------------------------------------------------------------------------
1567-- Concurrent Application
1568------------------------------------------------------------------------------
1570-- | Parallel transform application operator; applies a stream transformation
1571-- function @t m a -> t m b@ to a stream @t m a@ concurrently; the input stream
1572-- is evaluated asynchronously in an independent thread yielding elements to a
1573-- buffer and the transformation function runs in another thread consuming the
1574-- input from the buffer. '|$' is just like regular function application
1575-- operator '$' except that it is concurrent.
1577-- If you read the signature as @(t m a -> t m b) -> (t m a -> t m b)@ you can
1578-- look at it as a transformation that converts a transform function to a
1579-- buffered concurrent transform function.
1581-- The following code prints a value every second even though each stage adds a
1582-- 1 second delay.
1585-- >>> :{
1586-- Stream.drain $
1587-- Stream.mapM (\x -> threadDelay 1000000 >> print x)
1588-- |$ Stream.replicateM 3 (threadDelay 1000000 >> return 1)
1589-- :}
1590-- 1
1591-- 1
1592-- 1
1594-- /Concurrent/
1596-- /Since: 0.3.0 ("Streamly")/
1598-- @since 0.8.0
1599{-# INLINE (|$) #-}
1600(|$) :: (IsStream t, MonadAsync m) => (t m a -> t m b) -> (t m a -> t m b)
1601-- (|$) f = f . mkAsync
1602(|$) f = f . mkParallel
1604infixr 0 |$
1606-- | Same as '|$'.
1608-- /Internal/
1610{-# INLINE applyAsync #-}
1611applyAsync :: (IsStream t, MonadAsync m)
1612 => (t m a -> t m b) -> (t m a -> t m b)
1613applyAsync = (|$)
1615-- | Same as '|$' but with arguments reversed.
1617-- (|&) = flip (|$)
1619-- /Concurrent/
1621-- /Since: 0.3.0 ("Streamly")/
1623-- @since 0.8.0
1624{-# INLINE (|&) #-}
1625(|&) :: (IsStream t, MonadAsync m) => t m a -> (t m a -> t m b) -> t m b
1626x |& f = f |$ x
1628infixl 1 |&