on 6e77cdb help sign in
1623 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(..), 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
260import qualified Prelude
262import Prelude hiding
263 ( filter, drop, dropWhile, take, takeWhile, foldr, map, mapM, sequence
264 , reverse, foldr1 , scanl, scanl1, zipWith)
266--
267-- $setup
268-- >>> :m
269-- >>> import Control.Concurrent (threadDelay)
270-- >>> import Data.Function ((&))
271-- >>> import Streamly.Prelude ((|$))
272-- >>> import Prelude hiding ( filter, drop, dropWhile, take, takeWhile, foldr, map, mapM, sequence, reverse, foldr1 , scanl, scanl1)
273-- >>> import qualified Streamly.Prelude as Stream
274-- >>> import Streamly.Internal.Data.Stream.IsStream as Stream
275-- >>> import qualified Streamly.Data.Fold as Fold
276-- >>> import qualified Streamly.Internal.Data.Fold as Fold
277-- >>> import System.IO (stdout, hSetBuffering, BufferMode(LineBuffering))
278--
279-- >>> hSetBuffering stdout LineBuffering
281------------------------------------------------------------------------------
282-- Piping
283------------------------------------------------------------------------------
285-- | Use a 'Pipe' to transform a stream.
286--
287-- /Pre-release/
288--
289{-# INLINE transform #-}
290transform :: (IsStream t, Monad m) => Pipe m a b -> t m a -> t m b
291transform pipe xs = fromStreamD $ D.transform pipe (toStreamD xs)
293------------------------------------------------------------------------------
294-- Transformation Folds
295------------------------------------------------------------------------------
297-- | Right fold to a streaming monad.
298--
299-- > foldrS Stream.cons Stream.nil === id
300--
301-- 'foldrS' can be used to perform stateless stream to stream transformations
302-- like map and filter in general. It can be coupled with a scan to perform
303-- stateful transformations. However, note that the custom map and filter
304-- routines can be much more efficient than this due to better stream fusion.
305--
306-- >>> Stream.toList $ Stream.foldrS Stream.cons Stream.nil $ Stream.fromList [1..5]
307-- [1,2,3,4,5]
308--
309-- Find if any element in the stream is 'True':
310--
311-- >>> 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)
312-- [True]
313--
314-- Map (+2) on odd elements and filter out the even elements:
315--
316-- >>> 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)
317-- [3,5,7]
318--
319-- 'foldrM' can also be represented in terms of 'foldrS', however, the former
320-- is much more efficient:
321--
322-- > foldrM f z s = runIdentityT $ foldrS (\x xs -> lift $ f x (runIdentityT xs)) (lift z) s
323--
324-- /Pre-release/
325{-# INLINE foldrS #-}
326foldrS :: IsStream t => (a -> t m b -> t m b) -> t m b -> t m a -> t m b
327foldrS f z xs =
328 fromStream
329 $ K.foldrS
330 (\y ys -> toStream $ f y (fromStream ys))
331 (toStream z)
332 (toStream xs)
334{-# INLINE foldrSShared #-}
335foldrSShared :: IsStream t => (a -> t m b -> t m b) -> t m b -> t m a -> t m b
336foldrSShared f z xs =
337 fromStream
338 $ K.foldrSShared
339 (\y ys -> toStream $ f y (fromStream ys))
340 (toStream z)
341 (toStream xs)
343-- | Right fold to a transformer monad. This is the most general right fold
344-- function. 'foldrS' is a special case of 'foldrT', however 'foldrS'
345-- implementation can be more efficient:
346--
347-- > foldrS = foldrT
348-- > foldrM f z s = runIdentityT $ foldrT (\x xs -> lift $ f x (runIdentityT xs)) (lift z) s
349--
350-- 'foldrT' can be used to translate streamly streams to other transformer
351-- monads e.g. to a different streaming type.
352--
353-- /Pre-release/
354{-# INLINE foldrT #-}
355foldrT :: (IsStream t, Monad m, Monad (s m), MonadTrans s)
356 => (a -> s m b -> s m b) -> s m b -> t m a -> s m b
357foldrT f z s = D.foldrT f z (toStreamD s)
359------------------------------------------------------------------------------
360-- Transformation by Mapping
361------------------------------------------------------------------------------
363-- |
364-- @
365-- mapM f = sequence . map f
366-- @
367--
368-- Apply a monadic function to each element of the stream and replace it with
369-- the output of the resulting action.
370--
371-- @
372-- >>> drain $ Stream.mapM putStr $ Stream.fromList ["a", "b", "c"]
373-- abc
374--
375-- >>> :{
376-- drain $ Stream.replicateM 10 (return 1)
377-- & (fromSerial . Stream.mapM (\x -> threadDelay 1000000 >> print x))
378-- :}
379-- 1
380-- ...
381-- 1
382--
383-- > drain $ Stream.replicateM 10 (return 1)
384-- & (fromAsync . Stream.mapM (\x -> threadDelay 1000000 >> print x))
385-- @
386--
387-- /Concurrent (do not use with 'fromParallel' on infinite streams)/
388--
389-- @since 0.1.0
390{-# INLINE_EARLY mapM #-}
391mapM :: forall t m a b. (IsStream t, MonadAsync m) =>
392 (a -> m b) -> t m a -> t m b
393mapM f = fromStream . K.mapMWith (toConsK (consM @t)) f . toStream
395{-# RULES "mapM serial" mapM = mapMSerial #-}
396{-# INLINE mapMSerial #-}
397mapMSerial :: Monad m => (a -> m b) -> SerialT m a -> SerialT m b
398mapMSerial = Serial.mapM
400-- |
401-- @
402-- sequence = mapM id
403-- @
404--
405-- Replace the elements of a stream of monadic actions with the outputs of
406-- those actions.
407--
408-- @
409-- >>> drain $ Stream.sequence $ Stream.fromList [putStr "a", putStr "b", putStrLn "c"]
410-- abc
411--
412-- >>> :{
413-- drain $ Stream.replicateM 3 (return $ threadDelay 1000000 >> print 1)
414-- & (fromSerial . Stream.sequence)
415-- :}
416-- 1
417-- 1
418-- 1
419--
420-- >>> :{
421-- drain $ Stream.replicateM 3 (return $ threadDelay 1000000 >> print 1)
422-- & (fromAsync . Stream.sequence)
423-- :}
424-- 1
425-- 1
426-- 1
427--
428-- @
429--
430-- /Concurrent (do not use with 'fromParallel' on infinite streams)/
431--
432-- @since 0.1.0
433{-# INLINE sequence #-}
434sequence :: (IsStream t, MonadAsync m) => t m (m a) -> t m a
435sequence = mapM id
437------------------------------------------------------------------------------
438-- Mapping side effects
439------------------------------------------------------------------------------
441-- | Tap the data flowing through a stream into a 'Fold'. For example, you may
442-- add a tap to log the contents flowing through the stream. The fold is used
443-- only for effects, its result is discarded.
444--
445-- @
446-- Fold m a b
447-- |
448-- -----stream m a ---------------stream m a-----
449--
450-- @
451--
452-- >>> Stream.drain $ Stream.tap (Fold.drainBy print) (Stream.enumerateFromTo 1 2)
453-- 1
454-- 2
455--
456-- Compare with 'trace'.
457--
458-- @since 0.7.0
459{-# INLINE tap #-}
460tap :: (IsStream t, Monad m) => FL.Fold m a b -> t m a -> t m a
461tap f xs = fromStreamD $ D.tap f (toStreamD xs)
463-- XXX Remove this. It can be expressed in terms of Fold.sampleFromThen.
464--
465-- | @tapOffsetEvery offset n@ taps every @n@th element in the stream
466-- starting at @offset@. @offset@ can be between @0@ and @n - 1@. Offset 0
467-- means start at the first element in the stream. If the offset is outside
468-- this range then @offset `mod` n@ is used as offset.
469--
470-- >>> Stream.drain $ Stream.tapOffsetEvery 0 2 (Fold.rmapM print Fold.toList) $ Stream.enumerateFromTo 0 10
471-- [0,2,4,6,8,10]
473--
474-- /Pre-release/
475--
476{-# INLINE tapOffsetEvery #-}
477tapOffsetEvery :: (IsStream t, Monad m)
478 => Int -> Int -> FL.Fold m a b -> t m a -> t m a
479tapOffsetEvery offset n f xs =
480 fromStreamD $ D.tapOffsetEvery offset n f (toStreamD xs)
482-- | Redirect a copy of the stream to a supplied fold and run it concurrently
483-- in an independent thread. The fold may buffer some elements. The buffer size
484-- is determined by the prevailing 'maxBuffer' setting.
485--
486-- @
487-- Stream m a -> m b
488-- |
489-- -----stream m a ---------------stream m a-----
490--
491-- @
492--
493-- @
494-- >>> Stream.drain $ Stream.tapAsync (Fold.drainBy print) (Stream.enumerateFromTo 1 2)
495-- 1
496-- 2
497--
498-- @
499--
500-- Exceptions from the concurrently running fold are propagated to the current
501-- computation. Note that, because of buffering in the fold, exceptions may be
502-- delayed and may not correspond to the current element being processed in the
503-- parent stream, but we guarantee that before the parent stream stops the tap
504-- finishes and all exceptions from it are drained.
505--
506-- >>> tapAsync f = Stream.tapAsyncK (Stream.fold f . Stream.adapt)
507--
508-- Compare with 'tap'.
509--
510-- /Pre-release/
511{-# INLINE tapAsync #-}
512tapAsync :: (IsStream t, MonadAsync m) => FL.Fold m a b -> t m a -> t m a
513tapAsync f xs = fromStreamD $ Par.tapAsyncF f (toStreamD xs)
515-- XXX We should keep only tapAsyncK as tapAsync can be implemented in terms
516-- of tapAsyncK and it has better performance. Rename this to tapAsync.
518-- | Like 'tapAsyncF' but uses a stream fold function instead of a 'Fold' type.
519--
520-- /Pre-release/
521{-# INLINE tapAsyncK #-}
522tapAsyncK :: (IsStream t, MonadAsync m) => (t m a -> m b) -> t m a -> t m a
523tapAsyncK f m = fromStream $ Par.tapAsyncK (f . fromStream) (toStream m)
525-- XXX rename this to tapManyAsync_?
526--
527-- | Concurrently distribute a stream to a collection of fold functions,
528-- discarding the outputs of the folds.
529--
530-- @
531-- > Stream.drain $ Stream.distributeAsync_ [Stream.mapM_ print, Stream.mapM_ print] (Stream.enumerateFromTo 1 2)
532-- 1
533-- 2
534-- 1
535-- 2
536--
537-- @
538--
539-- @
540-- distributeAsync_ = flip (foldr tapAsync)
541-- @
542--
543-- /Pre-release/
544--
545{-# INLINE distributeAsync_ #-}
546distributeAsync_ :: (Foldable f, IsStream t, MonadAsync m)
547 => f (t m a -> m b) -> t m a -> t m a
548distributeAsync_ = flip (Prelude.foldr tapAsyncK)
550-- | @pollCounts predicate transform fold stream@ counts those elements in the
551-- stream that pass the @predicate@. The resulting count stream is sent to
552-- another thread which transforms it using @transform@ and then folds it using
553-- @fold@. The thread is automatically cleaned up if the stream stops or
554-- aborts due to exception.
555--
556-- For example, to print the count of elements processed every second:
557--
558-- @
559-- > Stream.drain $ Stream.pollCounts (const True) (Stream.rollingMap (-) . Stream.delayPost 1) (FLold.drainBy print)
560-- $ Stream.enumerateFrom 0
561-- @
562--
563-- Note: This may not work correctly on 32-bit machines.
564--
565-- /Pre-release/
566--
567{-# INLINE pollCounts #-}
568pollCounts ::
569 (IsStream t, MonadAsync m)
570 => (a -> Bool)
571 -> (t m Int -> m b)
572 -> t m a
573 -> t m a
574pollCounts predicate f xs =
575 fromStreamD
576 $ D.pollCounts predicate (f . fromStreamD)
577 $ toStreamD xs
579-- | Apply a monadic function to each element flowing through the stream and
580-- discard the results.
581--
582-- >>> Stream.drain $ Stream.trace print (Stream.enumerateFromTo 1 2)
583-- 1
584-- 2
585--
586-- Compare with 'tap'.
587--
588-- @since 0.7.0
589{-# INLINE trace #-}
590trace :: (IsStream t, MonadAsync m) => (a -> m b) -> t m a -> t m a
591trace f = mapM (\x -> void (f x) >> return x)
593-- | Perform a side effect before yielding each element of the stream and
594-- discard the results.
595--
596-- @
597-- >>> Stream.drain $ Stream.trace_ (print "got here") (Stream.enumerateFromTo 1 2)
598-- "got here"
599-- "got here"
600--
601-- @
602--
603-- Same as 'interspersePrefix_' but always serial.
604--
605-- See also: 'trace'
606--
607-- /Pre-release/
608{-# INLINE trace_ #-}
609trace_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
610trace_ eff = fromStreamD . D.mapM (\x -> eff >> return x) . toStreamD
612------------------------------------------------------------------------------
613-- Scanning with a Fold
614------------------------------------------------------------------------------
616-- | Scan a stream using the given monadic fold.
617--
618-- >>> Stream.toList $ Stream.takeWhile (< 10) $ Stream.scan Fold.sum (Stream.fromList [1..10])
619-- [0,1,3,6]
620--
621-- @since 0.7.0
622{-# INLINE scan #-}
623scan :: (IsStream t, Monad m) => Fold m a b -> t m a -> t m b
624scan fld m = fromStreamD $ D.scanOnce fld $ toStreamD m
626-- | Like 'scan' but restarts scanning afresh when the scanning fold
627-- terminates.
628--
629-- /Pre-release/
630{-# INLINE scanMany #-}
631scanMany :: (IsStream t, Monad m) => Fold m a b -> t m a -> t m b
632scanMany fld m = fromStreamD $ D.scanMany fld $ toStreamD m
634-- | Postscan a stream using the given monadic fold.
635--
636-- The following example extracts the input stream up to a point where the
637-- running average of elements is no more than 10:
638--
639-- >>> import Data.Maybe (fromJust)
640-- >>> let avg = Fold.teeWith (/) Fold.sum (fmap fromIntegral Fold.length)
641-- >>> :{
642-- Stream.toList
643-- $ Stream.map (fromJust . fst)
644-- $ Stream.takeWhile (\(_,x) -> x <= 10)
645-- $ Stream.postscan (Fold.tee Fold.last avg) (Stream.enumerateFromTo 1.0 100.0)
646-- :}
647-- [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]
648--
649-- @since 0.7.0
650{-# INLINE postscan #-}
651postscan :: (IsStream t, Monad m) => Fold m a b -> t m a -> t m b
652postscan fld = fromStreamD . D.postscanOnce fld . toStreamD
654------------------------------------------------------------------------------
655-- Scanning - Transformation by Folding
656------------------------------------------------------------------------------
658-- XXX It may be useful to have a version of scan where we can keep the
659-- accumulator independent of the value emitted. So that we do not necessarily
660-- have to keep a value in the accumulator which we are not using. We can pass
661-- an extraction function that will take the accumulator and the current value
662-- of the element and emit the next value in the stream. That will also make it
663-- possible to modify the accumulator after using it. In fact, the step function
664-- can return new accumulator and the value to be emitted. The signature would
665-- be more like mapAccumL. Or we can change the signature of scanx to
666-- accommodate this.
667--
668-- | Strict left scan with an extraction function. Like 'scanl'', but applies a
669-- user supplied extraction function (the third argument) at each step. This is
670-- designed to work with the @foldl@ library. The suffix @x@ is a mnemonic for
671-- extraction.
672--
673-- /Since 0.2.0/
674--
675-- /Since: 0.7.0 (Monad m constraint)/
676{-# DEPRECATED scanx "Please use scanl followed by map instead." #-}
677{-# INLINE scanx #-}
678scanx :: (IsStream t, Monad m) => (x -> a -> x) -> x -> (x -> b) -> t m a -> t m b
679scanx step begin done = fromStreamD . D.scanlx' step begin done . toStreamD
681-- XXX this needs to be concurrent
682-- XXX because of the use of D.cons for appending, scanlM' has quadratic
683-- complexity when iterated over a stream. We should use StreamK style scanlM'
684-- for linear performance on iteration.
685--
686-- | Like 'scanl'' but with a monadic step function and a monadic seed.
687--
688-- /Since: 0.4.0/
689--
690-- /Since: 0.8.0 (signature change)/
691{-# INLINE scanlM' #-}
692scanlM' :: (IsStream t, Monad m) => (b -> a -> m b) -> m b -> t m a -> t m b
693scanlM' step begin m = fromStreamD $ D.scanlM' step begin $ toStreamD m
695-- XXX because of the use of D.cons for appending, scanl' has quadratic
696-- complexity when iterated over a stream. We should use StreamK style scanlM'
697-- for linear performance on iteration.
699-- | Strict left scan. Like 'map', 'scanl'' too is a one to one transformation,
700-- however it adds an extra element.
701--
702-- @
703-- >>> Stream.toList $ Stream.scanl' (+) 0 $ fromList [1,2,3,4]
704-- [0,1,3,6,10]
705--
706-- @
707--
708-- @
709-- >>> Stream.toList $ Stream.scanl' (flip (:)) [] $ Stream.fromList [1,2,3,4]
710-- [[],[1],[2,1],[3,2,1],[4,3,2,1]]
711--
712-- @
713--
714-- The output of 'scanl'' is the initial value of the accumulator followed by
715-- all the intermediate steps and the final result of 'foldl''.
716--
717-- By streaming the accumulated state after each fold step, we can share the
718-- state across multiple stages of stream composition. Each stage can modify or
719-- extend the state, do some processing with it and emit it for the next stage,
720-- thus modularizing the stream processing. This can be useful in
721-- stateful or event-driven programming.
722--
723-- Consider the following monolithic example, computing the sum and the product
724-- of the elements in a stream in one go using a @foldl'@:
725--
726-- @
727-- >>> Stream.foldl' (\(s, p) x -> (s + x, p * x)) (0,1) $ Stream.fromList [1,2,3,4]
728-- (10,24)
729--
730-- @
731--
732-- Using @scanl'@ we can make it modular by computing the sum in the first
733-- stage and passing it down to the next stage for computing the product:
734--
735-- @
736-- >>> :{
737-- Stream.foldl' (\(_, p) (s, x) -> (s, p * x)) (0,1)
738-- $ Stream.scanl' (\(s, _) x -> (s + x, x)) (0,1)
739-- $ Stream.fromList [1,2,3,4]
740-- :}
741-- (10,24)
742--
743-- @
744--
745-- IMPORTANT: 'scanl'' evaluates the accumulator to WHNF. To avoid building
746-- lazy expressions inside the accumulator, it is recommended that a strict
747-- data structure is used for accumulator.
748--
749-- >>> scanl' step z = scan (Fold.foldl' step z)
750-- >>> scanl' f z xs = scanlM' (\a b -> return (f a b)) (return z) xs
751-- >>> scanl' f z xs = z `Stream.cons` postscanl' f z xs
752--
753-- See also: 'usingStateT'
754--
755-- @since 0.2.0
756{-# INLINE scanl' #-}
757scanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
758scanl' step z m = fromStreamD $ D.scanl' step z $ toStreamD m
760-- | Like 'scanl'' but does not stream the initial value of the accumulator.
761--
762-- >>> postscanl' step z = postscan (Fold.foldl' step z)
763-- >>> postscanl' f z = postscanlM' (\a b -> return (f a b)) (return z)
764-- >>> postscanl' f z xs = Stream.drop 1 $ Stream.scanl' f z xs
765--
766-- @since 0.7.0
767{-# INLINE postscanl' #-}
768postscanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
769postscanl' step z m = fromStreamD $ D.postscanl' step z $ toStreamD m
771-- XXX prescanl does not sound very useful, enable only if there is a
772-- compelling use case.
773--
774-- | Like scanl' but does not stream the final value of the accumulator.
775--
776-- /Pre-release/
777{-# INLINE prescanl' #-}
778prescanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
779prescanl' step z m = fromStreamD $ D.prescanl' step z $ toStreamD m
781-- XXX this needs to be concurrent
782-- | Like prescanl' but with a monadic step function and a monadic seed.
783--
784-- /Pre-release/
785{-# INLINE prescanlM' #-}
786prescanlM' :: (IsStream t, Monad m) => (b -> a -> m b) -> m b -> t m a -> t m b
787prescanlM' step z m = fromStreamD $ D.prescanlM' step z $ toStreamD m
789-- XXX this needs to be concurrent
790-- | Like 'scanl1'' but with a monadic step function.
791--
792-- @since 0.6.0
793{-# INLINE scanl1M' #-}
794scanl1M' :: (IsStream t, Monad m) => (a -> a -> m a) -> t m a -> t m a
795scanl1M' step m = fromStreamD $ D.scanl1M' step $ toStreamD m
797-- | Like 'scanl'' but for a non-empty stream. The first element of the stream
798-- is used as the initial value of the accumulator. Does nothing if the stream
799-- is empty.
800--
801-- @
802-- >>> Stream.toList $ Stream.scanl1' (+) $ fromList [1,2,3,4]
803-- [1,3,6,10]
804--
805-- @
806--
807-- @since 0.6.0
808{-# INLINE scanl1' #-}
809scanl1' :: (IsStream t, Monad m) => (a -> a -> a) -> t m a -> t m a
810scanl1' step m = fromStreamD $ D.scanl1' step $ toStreamD m
812------------------------------------------------------------------------------
813-- Filtering
814------------------------------------------------------------------------------
816-- | Modify a @t m a -> t m a@ stream transformation that accepts a predicate
817-- @(a -> b)@ to accept @((s, a) -> b)@ instead, provided a transformation @t m
818-- a -> t m (s, a)@. Convenient to filter with index or time.
819--
820-- @
821-- filterWithIndex = with indexed filter
822-- filterWithAbsTime = with timestamped filter
823-- filterWithRelTime = with timeIndexed filter
824-- @
825--
826-- /Pre-release/
827{-# INLINE with #-}
828with :: forall (t :: (Type -> Type) -> Type -> Type) m a b s. Functor (t m) =>
829 (t m a -> t m (s, a))
830 -> (((s, a) -> b) -> t m (s, a) -> t m (s, a))
831 -> (((s, a) -> b) -> t m a -> t m a)
832with f comb g = fmap snd . comb g . f
834-- | Include only those elements that pass a predicate.
835--
836-- @since 0.1.0
837{-# INLINE filter #-}
838filter :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m a
839filter p m = fromStreamD $ D.filter p $ toStreamD m
841-- | Same as 'filter' but with a monadic predicate.
842--
843-- @since 0.4.0
844{-# INLINE filterM #-}
845filterM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
846filterM p m = fromStreamD $ D.filterM p $ toStreamD m
848-- | Drop repeated elements that are adjacent to each other using the supplied
849-- comparison function.
850--
851-- @uniq = uniqBy (==)
852--
853-- To strip duplicate path separators:
854--
855-- @
856-- f x y = x == '/' && x == y
857-- Stream.toList $ Stream.uniqBy f $ Stream.fromList "//a//b"
858-- "/a/b"
859-- @
860--
861-- Space: @O(1)@
862--
863-- See also: 'nubBy'.
864--
865-- /Pre-release/
866--
867{-# INLINE uniqBy #-}
868uniqBy :: (IsStream t, Monad m, Functor (t m)) =>
869 (a -> a -> Bool) -> t m a -> t m a
870uniqBy eq = catMaybes . rollingMap f
872 where
874 f pre curr =
875 case pre of
876 Nothing -> Just curr
877 Just x -> if x `eq` curr then Nothing else Just curr
879-- | Drop repeated elements that are adjacent to each other.
880--
881-- @since 0.6.0
882{-# INLINE uniq #-}
883uniq :: (Eq a, IsStream t, Monad m) => t m a -> t m a
884uniq = fromStreamD . D.uniq . toStreamD
886-- | Strip all leading and trailing occurrences of an element passing a
887-- predicate and make all other consecutive occurrences uniq.
888--
889-- @
890-- prune p = dropWhileAround p $ uniqBy (x y -> p x && p y)
891-- @
892--
893-- @
894-- > Stream.prune isSpace (Stream.fromList " hello world! ")
895-- "hello world!"
896--
897-- @
898--
899-- Space: @O(1)@
900--
901-- /Unimplemented/
902{-# INLINE prune #-}
903prune ::
904 -- (IsStream t, Monad m, Eq a) =>
905 (a -> Bool) -> t m a -> t m a
906prune = error "Not implemented yet!"
908-- Possible implementation:
909-- @repeated =
910-- Stream.catMaybes . Stream.parseMany (Parser.groupBy (==) Fold.repeated)@
911--
912-- 'Fold.repeated' should return 'Just' when repeated, and 'Nothing' for a
913-- single element.
914--
915-- | Emit only repeated elements, once.
916--
917-- /Unimplemented/
918repeated :: -- (IsStream t, Monad m, Eq a) =>
919 t m a -> t m a
920repeated = undefined
922-- We can have more efficient implementations for nubOrd and nubInt by using
923-- Set and IntSet to find/remove duplication. For Hashable we can use a
924-- hashmap. Use rewrite rules to specialize to more efficient impls.
925--
926-- | Drop repeated elements anywhere in the stream.
927--
928-- /Caution: not scalable for infinite streams/
929--
930-- /See also: nubWindowBy/
931--
932-- /Unimplemented/
933--
934{-# INLINE nubBy #-}
935nubBy :: -- (IsStream t, Monad m) =>
936 (a -> a -> Bool) -> t m a -> t m a
937nubBy = undefined -- fromStreamD . D.nubBy . toStreamD
939-- | Deletes the first occurrence of the element in the stream that satisfies
940-- the given equality predicate.
941--
942-- @
943-- >>> Stream.toList $ Stream.deleteBy (==) 3 $ Stream.fromList [1,3,3,5]
944-- [1,3,5]
945--
946-- @
947--
948-- @since 0.6.0
949{-# INLINE deleteBy #-}
950deleteBy :: (IsStream t, Monad m) => (a -> a -> Bool) -> a -> t m a -> t m a
951deleteBy cmp x m = fromStreamD $ D.deleteBy cmp x (toStreamD m)
953------------------------------------------------------------------------------
954-- Lossy Buffering
955------------------------------------------------------------------------------
957-- XXX We could use 'maxBuffer Block/Drop/Rotate/Sample' instead. However we
958-- may want to have the evaluation rate independent of the sampling rate. To
959-- support that we can decouple evaluation and sampling in independent stages.
960-- The sampling stage would strictly evaluate and sample, the evaluation stage
961-- would control the evaluation rate.
963-- | Evaluate the input stream continuously and keep only the oldest @n@
964-- elements in the buffer, discard the new ones when the buffer is full. When
965-- the output stream is evaluated it consumes the values from the buffer in a
966-- FIFO manner.
967--
968-- /Unimplemented/
969--
970{-# INLINE sampleOld #-}
971sampleOld :: -- (IsStream t, Monad m) =>
972 Int -> t m a -> t m a
973sampleOld = undefined
975-- | Evaluate the input stream continuously and keep only the latest @n@
976-- elements in a ring buffer, keep discarding the older ones to make space for
977-- the new ones. When the output stream is evaluated it consumes the values
978-- from the buffer in a FIFO manner.
979--
980-- /Unimplemented/
981--
982{-# INLINE sampleNew #-}
983sampleNew :: -- (IsStream t, Monad m) =>
984 Int -> t m a -> t m a
985sampleNew = undefined
987-- | Like 'sampleNew' but samples at uniform intervals to match the consumer
988-- rate. Note that 'sampleNew' leads to non-uniform sampling depending on the
989-- consumer pattern.
990--
991-- /Unimplemented/
992--
993{-# INLINE sampleRate #-}
994sampleRate :: -- (IsStream t, Monad m) =>
995 Double -> t m a -> t m a
996sampleRate = undefined
998------------------------------------------------------------------------------
999-- Trimming
1000------------------------------------------------------------------------------
1002-- | Same as 'takeWhile' but with a monadic predicate.
1004-- @since 0.4.0
1005{-# INLINE takeWhileM #-}
1006takeWhileM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
1007takeWhileM p m = fromStreamD $ D.takeWhileM p $ toStreamD m
1009-- See the lastN fold for impl hints. Use a Data.Array based ring buffer.
1011-- takeLast n = Stream.concatM . fmap Array.toStream . fold Fold.lastN
1013-- | Take @n@ elements at the end of the stream.
1015-- O(n) space, where n is the number elements taken.
1017-- /Unimplemented/
1018{-# INLINE takeLast #-}
1019takeLast :: -- (IsStream t, Monad m) =>
1020 Int -> t m a -> t m a
1021takeLast = undefined -- fromStreamD $ D.takeLast n $ toStreamD m
1023-- | Take time interval @i@ seconds at the end of the stream.
1025-- O(n) space, where n is the number elements taken.
1027-- /Unimplemented/
1028{-# INLINE takeLastInterval #-}
1029takeLastInterval :: -- (IsStream t, Monad m) =>
1030 Double -> t m a -> t m a
1031takeLastInterval = undefined -- fromStreamD $ D.takeLast n $ toStreamD m
1033-- | Take all consecutive elements at the end of the stream for which the
1034-- predicate is true.
1036-- O(n) space, where n is the number elements taken.
1038-- /Unimplemented/
1039{-# INLINE takeWhileLast #-}
1040takeWhileLast :: -- (IsStream t, Monad m) =>
1041 (a -> Bool) -> t m a -> t m a
1042takeWhileLast = undefined -- fromStreamD $ D.takeWhileLast n $ toStreamD m
1044-- | Like 'takeWhile' and 'takeWhileLast' combined.
1046-- O(n) space, where n is the number elements taken from the end.
1048-- /Unimplemented/
1049{-# INLINE takeWhileAround #-}
1050takeWhileAround :: -- (IsStream t, Monad m) =>
1051 (a -> Bool) -> t m a -> t m a
1052takeWhileAround = undefined -- fromStreamD $ D.takeWhileAround n $ toStreamD m
1054-- | @takeInterval duration@ yields stream elements upto specified time
1055-- @duration@. The duration starts when the stream is evaluated for the first
1056-- time, before the first element is yielded. The time duration is checked
1057-- before generating each element, if the duration has expired the stream
1058-- stops.
1060-- The total time taken in executing the stream is guaranteed to be /at least/
1061-- @duration@, however, because the duration is checked before generating an
1062-- element, the upper bound is indeterminate and depends on the time taken in
1063-- generating and processing the last element.
1065-- No element is yielded if the duration is zero. At least one element is
1066-- yielded if the duration is non-zero.
1068-- /Pre-release/
1070{-# INLINE takeInterval #-}
1071takeInterval ::(MonadIO m, IsStream t, TimeUnit64 d) => d -> t m a -> t m a
1072takeInterval d = fromStreamD . D.takeByTime d . toStreamD
1074-- | Drop elements in the stream as long as the predicate succeeds and then
1075-- take the rest of the stream.
1077-- @since 0.1.0
1078{-# INLINE dropWhile #-}
1079dropWhile :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m a
1080dropWhile p m = fromStreamD $ D.dropWhile p $ toStreamD m
1082-- | Same as 'dropWhile' but with a monadic predicate.
1084-- @since 0.4.0
1085{-# INLINE dropWhileM #-}
1086dropWhileM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
1087dropWhileM p m = fromStreamD $ D.dropWhileM p $ toStreamD m
1089-- | @dropInterval duration@ drops stream elements until specified @duration@ has
1090-- passed. The duration begins when the stream is evaluated for the first
1091-- time. The time duration is checked /after/ generating a stream element, the
1092-- element is yielded if the duration has expired otherwise it is dropped.
1094-- The time elapsed before starting to generate the first element is /at most/
1095-- @duration@, however, because the duration expiry is checked after the
1096-- element is generated, the lower bound is indeterminate and depends on the
1097-- time taken in generating an element.
1099-- All elements are yielded if the duration is zero.
1101-- /Pre-release/
1103{-# INLINE dropInterval #-}
1104dropInterval ::(MonadIO m, IsStream t, TimeUnit64 d) => d -> t m a -> t m a
1105dropInterval d = fromStreamD . D.dropByTime d . toStreamD
1107-- | Drop @n@ elements at the end of the stream.
1109-- O(n) space, where n is the number elements dropped.
1111-- /Unimplemented/
1112{-# INLINE dropLast #-}
1113dropLast :: -- (IsStream t, Monad m) =>
1114 Int -> t m a -> t m a
1115dropLast = undefined -- fromStreamD $ D.dropLast n $ toStreamD m
1117-- | Drop time interval @i@ seconds at the end of the stream.
1119-- O(n) space, where n is the number elements dropped.
1121-- /Unimplemented/
1122{-# INLINE dropLastInterval #-}
1123dropLastInterval :: -- (IsStream t, Monad m) =>
1124 Int -> t m a -> t m a
1125dropLastInterval = undefined
1127-- | Drop all consecutive elements at the end of the stream for which the
1128-- predicate is true.
1130-- O(n) space, where n is the number elements dropped.
1132-- /Unimplemented/
1133{-# INLINE dropWhileLast #-}
1134dropWhileLast :: -- (IsStream t, Monad m) =>
1135 (a -> Bool) -> t m a -> t m a
1136dropWhileLast = undefined -- fromStreamD $ D.dropWhileLast n $ toStreamD m
1138-- | Like 'dropWhile' and 'dropWhileLast' combined.
1140-- O(n) space, where n is the number elements dropped from the end.
1142-- /Unimplemented/
1143{-# INLINE dropWhileAround #-}
1144dropWhileAround :: -- (IsStream t, Monad m) =>
1145 (a -> Bool) -> t m a -> t m a
1146dropWhileAround = undefined -- fromStreamD $ D.dropWhileAround n $ toStreamD m
1148------------------------------------------------------------------------------
1149-- Inserting Elements
1150------------------------------------------------------------------------------
1152-- | @insertBy cmp elem stream@ inserts @elem@ before the first element in
1153-- @stream@ that is less than @elem@ when compared using @cmp@.
1155-- @
1156-- insertBy cmp x = 'mergeBy' cmp ('fromPure' x)
1157-- @
1159-- @
1160-- >>> Stream.toList $ Stream.insertBy compare 2 $ Stream.fromList [1,3,5]
1161-- [1,2,3,5]
1163-- @
1165-- @since 0.6.0
1166{-# INLINE insertBy #-}
1167insertBy ::
1168 (IsStream t, Monad m) => (a -> a -> Ordering) -> a -> t m a -> t m a
1169insertBy cmp x m = fromStreamD $ D.insertBy cmp x (toStreamD m)
1171-- | Insert a pure value between successive elements of a stream.
1173-- >>> Stream.toList $ Stream.intersperse ',' $ Stream.fromList "hello"
1174-- "h,e,l,l,o"
1176-- @since 0.7.0
1177{-# INLINE intersperse #-}
1178intersperse :: (IsStream t, MonadAsync m) => a -> t m a -> t m a
1179intersperse a = fromStreamD . D.intersperse a . toStreamD
1181-- | Insert a side effect before consuming an element of a stream except the
1182-- first one.
1184-- >>> Stream.drain $ Stream.trace putChar $ Stream.intersperseM_ (putChar '.') $ Stream.fromList "hello"
1185-- h.e.l.l.o
1187-- /Pre-release/
1188{-# INLINE intersperseM_ #-}
1189intersperseM_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
1190intersperseM_ m = fromStreamD . D.intersperseM_ m . toStreamD
1192-- | Intersperse a monadic action into the input stream after every @n@
1193-- elements.
1195-- @
1196-- > Stream.toList $ Stream.intersperseBySpan 2 (return ',') $ Stream.fromList "hello"
1197-- "he,ll,o"
1199-- @
1201-- /Unimplemented/
1202{-# INLINE intersperseBySpan #-}
1203intersperseBySpan :: -- IsStream t =>
1204 Int -> m a -> t m a -> t m a
1205intersperseBySpan _n _f _xs = undefined
1207-- | Insert an effect and its output after consuming an element of a stream.
1209-- >>> Stream.toList $ Stream.trace putChar $ intersperseSuffix (putChar '.' >> return ',') $ Stream.fromList "hello"
1210-- h.,e.,l.,l.,o.,"h,e,l,l,o,"
1212-- /Pre-release/
1213{-# INLINE intersperseSuffix #-}
1214intersperseSuffix :: (IsStream t, Monad m) => m a -> t m a -> t m a
1215intersperseSuffix m = fromStreamD . D.intersperseSuffix m . toStreamD
1217-- | Insert a side effect after consuming an element of a stream.
1219-- @
1220-- >>> Stream.mapM_ putChar $ Stream.intersperseSuffix_ (threadDelay 1000000) $ Stream.fromList "hello"
1221-- hello
1223-- @
1225-- /Pre-release/
1227{-# INLINE intersperseSuffix_ #-}
1228intersperseSuffix_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
1229intersperseSuffix_ m = fromStreamD . D.intersperseSuffix_ m . toStreamD
1231-- XXX Use an offset argument, like tapOffsetEvery
1233-- | Like 'intersperseSuffix' but intersperses an effectful action into the
1234-- input stream after every @n@ elements and after the last element.
1236-- >>> Stream.toList $ Stream.intersperseSuffixBySpan 2 (return ',') $ Stream.fromList "hello"
1237-- "he,ll,o,"
1239-- /Pre-release/
1241{-# INLINE intersperseSuffixBySpan #-}
1242intersperseSuffixBySpan :: (IsStream t, Monad m)
1243 => Int -> m a -> t m a -> t m a
1244intersperseSuffixBySpan n eff =
1245 fromStreamD . D.intersperseSuffixBySpan n eff . toStreamD
1247-- | Insert a side effect before consuming an element of a stream.
1249-- >>> Stream.toList $ Stream.trace putChar $ Stream.interspersePrefix_ (putChar '.' >> return ',') $ Stream.fromList "hello"
1250-- .h.e.l.l.o"hello"
1252-- Same as 'trace_' but may be concurrent.
1254-- /Concurrent/
1256-- /Pre-release/
1258{-# INLINE interspersePrefix_ #-}
1259interspersePrefix_ :: (IsStream t, MonadAsync m) => m b -> t m a -> t m a
1260interspersePrefix_ m = mapM (\x -> void m >> return x)
1262------------------------------------------------------------------------------
1263-- Inserting Time
1264------------------------------------------------------------------------------
1266-- Note: delay must be serial.
1268-- | Introduce a delay of specified seconds before consuming an element of the
1269-- stream except the first one.
1271-- >>> Stream.mapM_ print $ Stream.timestamped $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
1272-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),1)
1273-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),2)
1274-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),3)
1276-- @since 0.8.0
1278{-# INLINE delay #-}
1279delay :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
1280delay n = intersperseM_ $ liftIO $ threadDelay $ round $ n * 1000000
1282-- Note: delay must be serial.
1284-- | Introduce a delay of specified seconds after consuming an element of a
1285-- stream.
1287-- >>> Stream.mapM_ print $ Stream.timestamped $ Stream.delayPost 1 $ Stream.enumerateFromTo 1 3
1288-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),1)
1289-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),2)
1290-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),3)
1292-- /Pre-release/
1294{-# INLINE delayPost #-}
1295delayPost :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
1296delayPost n = intersperseSuffix_ $ liftIO $ threadDelay $ round $ n * 1000000
1298-- Note: delay must be serial, that's why 'trace_' is used.
1300-- | Introduce a delay of specified seconds before consuming an element of a
1301-- stream.
1303-- >>> Stream.mapM_ print $ Stream.timestamped $ Stream.delayPre 1 $ Stream.enumerateFromTo 1 3
1304-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),1)
1305-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),2)
1306-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),3)
1308-- /Pre-release/
1310{-# INLINE delayPre #-}
1311delayPre :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
1312delayPre n = trace_ $ liftIO $ threadDelay $ round $ n * 1000000
1314------------------------------------------------------------------------------
1315-- Reorder in sequence
1316------------------------------------------------------------------------------
1318-- | Buffer until the next element in sequence arrives. The function argument
1319-- determines the difference in sequence numbers. This could be useful in
1320-- implementing sequenced streams, for example, TCP reassembly.
1322-- /Unimplemented/
1324{-# INLINE reassembleBy #-}
1325reassembleBy
1326 :: -- (IsStream t, Monad m) =>
1327 Fold m a b
1328 -> (a -> a -> Int)
1329 -> t m a
1330 -> t m b
1331reassembleBy = undefined
1333------------------------------------------------------------------------------
1334-- Position Indexing
1335------------------------------------------------------------------------------
1337-- |
1338-- > indexed = Stream.postscanl' (\(i, _) x -> (i + 1, x)) (-1,undefined)
1339-- > indexed = Stream.zipWith (,) (Stream.enumerateFrom 0)
1341-- Pair each element in a stream with its index, starting from index 0.
1343-- >>> Stream.toList $ Stream.indexed $ Stream.fromList "hello"
1344-- [(0,'h'),(1,'e'),(2,'l'),(3,'l'),(4,'o')]
1346-- @since 0.6.0
1347{-# INLINE indexed #-}
1348indexed :: (IsStream t, Monad m) => t m a -> t m (Int, a)
1349indexed = fromStreamD . D.indexed . toStreamD
1351-- |
1352-- > indexedR n = Stream.postscanl' (\(i, _) x -> (i - 1, x)) (n + 1,undefined)
1353-- > indexedR n = Stream.zipWith (,) (Stream.enumerateFromThen n (n - 1))
1355-- Pair each element in a stream with its index, starting from the
1356-- given index @n@ and counting down.
1358-- >>> Stream.toList $ Stream.indexedR 10 $ Stream.fromList "hello"
1359-- [(10,'h'),(9,'e'),(8,'l'),(7,'l'),(6,'o')]
1361-- @since 0.6.0
1362{-# INLINE indexedR #-}
1363indexedR :: (IsStream t, Monad m) => Int -> t m a -> t m (Int, a)
1364indexedR n = fromStreamD . D.indexedR n . toStreamD
1366-------------------------------------------------------------------------------
1367-- Time Indexing
1368-------------------------------------------------------------------------------
1370-- Note: The timestamp stream must be the second stream in the zip so that the
1371-- timestamp is generated after generating the stream element and not before.
1372-- If we do not do that then the following example will generate the same
1373-- timestamp for first two elements:
1375-- Stream.mapM_ print $ Stream.timestamped $ Stream.delay $ Stream.enumerateFromTo 1 3
1377-- | Pair each element in a stream with an absolute timestamp, using a clock of
1378-- specified granularity. The timestamp is generated just before the element
1379-- is consumed.
1381-- >>> Stream.mapM_ print $ Stream.timestampWith 0.01 $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
1382-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),1)
1383-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),2)
1384-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),3)
1386-- /Pre-release/
1388{-# INLINE timestampWith #-}
1389timestampWith :: (IsStream t, MonadAsync m, Functor (t m))
1390 => Double -> t m a -> t m (AbsTime, a)
1391timestampWith g stream = zipWith (flip (,)) stream (absTimesWith g)
1393-- TBD: check performance vs a custom implementation without using zipWith.
1395-- /Pre-release/
1397{-# INLINE timestamped #-}
1398timestamped :: (IsStream t, MonadAsync m, Functor (t m))
1399 => t m a -> t m (AbsTime, a)
1400timestamped = timestampWith 0.01
1402-- | Pair each element in a stream with relative times starting from 0, using a
1403-- clock with the specified granularity. The time is measured just before the
1404-- element is consumed.
1406-- >>> Stream.mapM_ print $ Stream.timeIndexWith 0.01 $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
1407-- (RelTime64 (NanoSecond64 ...),1)
1408-- (RelTime64 (NanoSecond64 ...),2)
1409-- (RelTime64 (NanoSecond64 ...),3)
1411-- /Pre-release/
1413{-# INLINE timeIndexWith #-}
1414timeIndexWith :: (IsStream t, MonadAsync m, Functor (t m))
1415 => Double -> t m a -> t m (RelTime64, a)
1416timeIndexWith g stream = zipWith (flip (,)) stream (relTimesWith g)
1418-- | Pair each element in a stream with relative times starting from 0, using a
1419-- 10 ms granularity clock. The time is measured just before the element is
1420-- consumed.
1422-- >>> Stream.mapM_ print $ Stream.timeIndexed $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
1423-- (RelTime64 (NanoSecond64 ...),1)
1424-- (RelTime64 (NanoSecond64 ...),2)
1425-- (RelTime64 (NanoSecond64 ...),3)
1427-- /Pre-release/
1429{-# INLINE timeIndexed #-}
1430timeIndexed :: (IsStream t, MonadAsync m, Functor (t m))
1431 => t m a -> t m (RelTime64, a)
1432timeIndexed = timeIndexWith 0.01
1434------------------------------------------------------------------------------
1435-- Searching
1436------------------------------------------------------------------------------
1438-- | Find all the indices where the value of the element in the stream is equal
1439-- to the given value.
1441-- > elemIndices a = findIndices (== a)
1443-- @since 0.5.0
1444{-# INLINE elemIndices #-}
1445elemIndices :: (IsStream t, Eq a, Monad m) => a -> t m a -> t m Int
1446elemIndices a = findIndices (== a)
1448------------------------------------------------------------------------------
1449-- Rolling map
1450------------------------------------------------------------------------------
1452-- XXX this is not a one-to-one map so calling it map may not be right.
1453-- We can perhaps call it zipWithTail or rollWith.
1455-- | Apply a function on every two successive elements of a stream. The first
1456-- argument of the map function is the previous element and the second argument
1457-- is the current element. When the current element is the first element, the
1458-- previous element is 'Nothing'.
1460-- /Pre-release/
1462{-# INLINE rollingMap #-}
1463rollingMap :: (IsStream t, Monad m) => (Maybe a -> a -> b) -> t m a -> t m b
1464rollingMap f m = fromStreamD $ D.rollingMap f $ toStreamD m
1466-- | Like 'rollingMap' but with an effectful map function.
1468-- /Pre-release/
1470{-# INLINE rollingMapM #-}
1471rollingMapM :: (IsStream t, Monad m) => (Maybe a -> a -> m b) -> t m a -> t m b
1472rollingMapM f m = fromStreamD $ D.rollingMapM f $ toStreamD m
1474-- | Like 'rollingMap' but requires at least two elements in the stream,
1475-- returns an empty stream otherwise.
1477-- This is the stream equivalent of the list idiom @zipWith f xs (tail xs)@.
1479-- /Pre-release/
1481{-# INLINE rollingMap2 #-}
1482rollingMap2 :: (IsStream t, Monad m) => (a -> a -> b) -> t m a -> t m b
1483rollingMap2 f m = fromStreamD $ D.rollingMap2 f $ toStreamD m
1485------------------------------------------------------------------------------
1486-- Maybe Streams
1487------------------------------------------------------------------------------
1489-- | Map a 'Maybe' returning function to a stream, filter out the 'Nothing'
1490-- elements, and return a stream of values extracted from 'Just'.
1492-- Equivalent to:
1494-- @
1495-- mapMaybe f = Stream.map 'fromJust' . Stream.filter 'isJust' . Stream.map f
1496-- @
1498-- @since 0.3.0
1499{-# INLINE mapMaybe #-}
1500mapMaybe :: (IsStream t, Monad m) => (a -> Maybe b) -> t m a -> t m b
1501mapMaybe f m = fromStreamD $ D.mapMaybe f $ toStreamD m
1503-- | Like 'mapMaybe' but maps a monadic function.
1505-- Equivalent to:
1507-- @
1508-- mapMaybeM f = Stream.map 'fromJust' . Stream.filter 'isJust' . Stream.mapM f
1509-- @
1511-- /Concurrent (do not use with 'fromParallel' on infinite streams)/
1513-- @since 0.3.0
1514{-# INLINE_EARLY mapMaybeM #-}
1515mapMaybeM :: (IsStream t, MonadAsync m, Functor (t m))
1516 => (a -> m (Maybe b)) -> t m a -> t m b
1517mapMaybeM f = fmap fromJust . filter isJust . mapM f
1519{-# RULES "mapMaybeM serial" mapMaybeM = mapMaybeMSerial #-}
1520{-# INLINE mapMaybeMSerial #-}
1521mapMaybeMSerial :: Monad m => (a -> m (Maybe b)) -> SerialT m a -> SerialT m b
1522mapMaybeMSerial f m = fromStreamD $ D.mapMaybeM f $ toStreamD m
1524-- | In a stream of 'Maybe's, discard 'Nothing's and unwrap 'Just's.
1526-- /Pre-release/
1528{-# INLINE catMaybes #-}
1529catMaybes :: (IsStream t, Monad m, Functor (t m)) => t m (Maybe a) -> t m a
1530catMaybes = fmap fromJust . filter isJust
1532------------------------------------------------------------------------------
1533-- Either streams
1534------------------------------------------------------------------------------
1536-- | Discard 'Right's and unwrap 'Left's in an 'Either' stream.
1538-- /Pre-release/
1540{-# INLINE lefts #-}
1541lefts :: (IsStream t, Monad m, Functor (t m)) => t m (Either a b) -> t m a
1542lefts = fmap (fromLeft undefined) . filter isLeft
1544-- | Discard 'Left's and unwrap 'Right's in an 'Either' stream.
1546-- /Pre-release/
1548{-# INLINE rights #-}
1549rights :: (IsStream t, Monad m, Functor (t m)) => t m (Either a b) -> t m b
1550rights = fmap (fromRight undefined) . filter isRight
1552-- | Remove the either wrapper and flatten both lefts and as well as rights in
1553-- the output stream.
1555-- /Pre-release/
1557{-# INLINE both #-}
1558both :: Functor (t m) => t m (Either a a) -> t m a
1559both = fmap (either id id)
1561------------------------------------------------------------------------------
1562-- Concurrent Application
1563------------------------------------------------------------------------------
1565-- | Parallel transform application operator; applies a stream transformation
1566-- function @t m a -> t m b@ to a stream @t m a@ concurrently; the input stream
1567-- is evaluated asynchronously in an independent thread yielding elements to a
1568-- buffer and the transformation function runs in another thread consuming the
1569-- input from the buffer. '|$' is just like regular function application
1570-- operator '$' except that it is concurrent.
1572-- If you read the signature as @(t m a -> t m b) -> (t m a -> t m b)@ you can
1573-- look at it as a transformation that converts a transform function to a
1574-- buffered concurrent transform function.
1576-- The following code prints a value every second even though each stage adds a
1577-- 1 second delay.
1580-- >>> :{
1581-- Stream.drain $
1582-- Stream.mapM (\x -> threadDelay 1000000 >> print x)
1583-- |$ Stream.replicateM 3 (threadDelay 1000000 >> return 1)
1584-- :}
1585-- 1
1586-- 1
1587-- 1
1589-- /Concurrent/
1591-- /Since: 0.3.0 ("Streamly")/
1593-- @since 0.8.0
1594{-# INLINE (|$) #-}
1595(|$) :: (IsStream t, MonadAsync m) => (t m a -> t m b) -> (t m a -> t m b)
1596-- (|$) f = f . mkAsync
1597(|$) f = f . mkParallel
1599infixr 0 |$
1601-- | Same as '|$'.
1603-- /Internal/
1605{-# INLINE applyAsync #-}
1606applyAsync :: (IsStream t, MonadAsync m)
1607 => (t m a -> t m b) -> (t m a -> t m b)
1608applyAsync = (|$)
1610-- | Same as '|$' but with arguments reversed.
1612-- (|&) = flip (|$)
1614-- /Concurrent/
1616-- /Since: 0.3.0 ("Streamly")/
1618-- @since 0.8.0
1619{-# INLINE (|&) #-}
1620(|&) :: (IsStream t, MonadAsync m) => t m a -> (t m a -> t m b) -> t m b
1621x |& f = f |$ x
1623infixl 1 |&