on c93bad0 help sign in
1534 lines 48 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 , foldrT
19 -- * Mapping
20 -- | Stateless one-to-one maps.
21 , Serial.map
22 , sequence
23 , mapM
24 , smapM
26 -- * Mapping Side Effects (Observation)
27 -- | See also the intersperse*_ combinators.
28 , trace
29 , trace_
30 , tap
31 , tapOffsetEvery
32 , tapAsync
33 , tapRate
34 , pollCounts
36 -- * Scanning By 'Fold'
37 , scan
38 , postscan
40 -- * Scanning
41 -- | Left scans. Stateful, mostly one-to-one maps.
42 , scanl'
43 , scanlM'
44 , scanlMAfter'
45 , postscanl'
46 , postscanlM'
47 , prescanl'
48 , prescanlM'
49 , scanl1'
50 , scanl1M'
52 -- XXX Once we have pipes the contravariant transformations can be
53 -- represented by attaching pipes before a transformation.
54 --
55 -- , lscanl'
56 -- , lscanlM'
57 -- , lscanl1'
58 -- , lscanl1M'
59 --
60 -- , lpostscanl'
61 -- , lpostscanlM'
62 -- , lprescanl'
63 -- , lprescanlM'
65 -- * Filtering
66 -- | Produce a subset of the stream using criteria based on the values of
67 -- the elements. We can use a concatMap and scan for filtering but these
68 -- combinators are more efficient and convenient.
70 , with
71 , deleteBy
72 , filter
73 , filterM
74 , uniq
75 , uniqBy
76 , nubBy
77 , nubWindowBy
78 , prune
79 , repeated
81 -- * Trimming
82 -- | Produce a subset of the stream trimmed at ends.
84 , take
85 , takeByTime -- takeInterval
86 , takeEnd
87 , takeEndInterval
88 , takeWhile
89 , takeWhileM
90 , takeWhileEnd
91 , takeWhileAround
92 , drop
93 , dropByTime -- dropInterval
94 , dropEnd
95 , dropEndInterval
96 , dropWhile
97 , dropWhileM
98 , dropWhileEnd
99 , dropWhileAround
101 -- * Inserting Elements
102 -- | Produce a superset of the stream. This is the opposite of
103 -- filtering/sampling. We can always use concatMap and scan for inserting
104 -- but these combinators are more efficient and convenient.
106 -- Element agnostic (Opposite of sampling)
107 , intersperse
108 , intersperseM -- XXX naming
109 , intersperseBySpan
111 , intersperseSuffix
112 , intersperseSuffixBySpan
113 , interjectSuffix
115 -- , interspersePrefix
116 -- , interspersePrefixBySpan
118 -- * Inserting Side Effects/Time
119 , intersperseM_ -- XXX naming
120 , delay
121 , intersperseSuffix_
122 , delayPost
123 , interspersePrefix_
124 , delayPre
126 -- * Element Aware Insertion
127 -- | Opposite of filtering
128 , insertBy
129 -- , intersperseByBefore
130 -- , intersperseByAfter
132 -- * Reordering
133 , reverse
134 , reverse'
135 , reassembleBy
137 -- * Position Indexing
138 , indexed
139 , indexedR
141 -- * Time Indexing
142 , timestamped
143 , timestampWith
144 -- , timestampedR -- timer
145 , timeIndexed
146 , timeIndexWith
148 -- * Searching
149 , findIndices -- XXX indicesBy
150 , elemIndices -- XXX indicesOf
152 -- * Rolling map
153 -- | Map using the previous element.
154 , rollingMapM
155 , rollingMap
157 -- * Maybe Streams
158 -- Move these to Streamly.Data.Maybe.Stream?
159 , catMaybes -- XXX justs (like lefts/rights)
160 , mapMaybe
161 , mapMaybeM
163 -- * Either Streams
164 -- Move these to Streamly.Data.Either.Stream?
165 , lefts
166 , rights
168 -- * Concurrent Evaluation
169 -- ** Concurrent Pipelines
170 -- | Run streaming stages concurrently.
172 , Par.mkParallel
173 , applyAsync
174 , (|$)
175 , (|&)
177 -- ** Concurrency Control
178 , maxThreads
180 -- ** Buffering and Sampling
181 -- | Evaluate strictly using a buffer of results. When the buffer becomes
182 -- full we can block, drop the new elements, drop the oldest element and
183 -- insert the new at the end or keep dropping elements uniformly to match
184 -- the rate of the consumer.
185 , maxBuffer
186 , sampleOld
187 , sampleNew
188 , sampleRate
190 -- ** Rate Limiting
191 -- | Evaluate the stream at uniform intervals to maintain a specified
192 -- evaluation rate.
193 , Rate (..)
194 , rate
195 , avgRate
196 , minRate
197 , maxRate
198 , constRate
200 -- * Diagnostics
201 , inspectMode
203 -- * Deprecated
204 , scanx
205 )
206where
208#include "inline.hs"
210import Control.Concurrent (threadDelay)
211import Control.Monad (void)
212import Control.Monad.Catch (MonadCatch)
213import Control.Monad.IO.Class (MonadIO(..))
214import Control.Monad.Trans.Class (MonadTrans(..))
215import Data.Either (isLeft, isRight)
216import Data.Kind (Type)
217import Data.Maybe (isJust, fromJust)
218import Streamly.Internal.BaseCompat (fromLeft, fromRight)
219import Streamly.Internal.Data.Fold.Types (Fold (..))
220import Streamly.Internal.Data.Pipe.Types (Pipe (..))
221import Streamly.Internal.Data.Stream.IsStream.Combinators
222 ( inspectMode, maxBuffer, maxThreads, rate, avgRate, minRate
223 , maxRate, constRate)
224import Streamly.Internal.Data.Stream.IsStream.Common
225 ( absTimesWith
226 , drop
227 , findIndices
228 , postscanlM'
229 , relTimesWith
230 , reverse
231 , reverse'
232 , scanlMAfter'
233 , smapM
234 , take
235 , takeWhile
236 , interjectSuffix
237 , intersperseM
238 )
239import Streamly.Internal.Data.Stream.Prelude (fromStreamS, toStreamS)
240import Streamly.Internal.Data.Stream.Serial (SerialT)
241import Streamly.Internal.Data.Stream.StreamD (fromStreamD, toStreamD)
242import Streamly.Internal.Data.Stream.StreamK (IsStream)
243import Streamly.Internal.Data.SVar (MonadAsync, Rate(..))
244import Streamly.Internal.Data.Time.Units (TimeUnit64, AbsTime, RelTime64)
246import qualified Streamly.Internal.Data.Fold as FL
247import qualified Streamly.Internal.Data.Stream.Parallel as Par
248import qualified Streamly.Internal.Data.Stream.Prelude as P
249import qualified Streamly.Internal.Data.Stream.Serial as Serial
250import qualified Streamly.Internal.Data.Stream.StreamD as D
251import qualified Streamly.Internal.Data.Stream.StreamK as K
252import qualified Streamly.Internal.Data.Stream.Zip as Z
253#ifdef USE_STREAMK_ONLY
254import qualified Streamly.Internal.Data.Stream.StreamK as S
255#else
256import qualified Streamly.Internal.Data.Stream.StreamD as S
257#endif
259import Prelude hiding
260 ( filter, drop, dropWhile, take, takeWhile, foldr, map, mapM, sequence
261 , reverse, foldr1 , scanl, scanl1)
263------------------------------------------------------------------------------
264-- Piping
265------------------------------------------------------------------------------
267-- | Use a 'Pipe' to transform a stream.
268--
269-- /Internal/
270--
271{-# INLINE transform #-}
272transform :: (IsStream t, Monad m) => Pipe m a b -> t m a -> t m b
273transform pipe xs = fromStreamD $ D.transform pipe (toStreamD xs)
275------------------------------------------------------------------------------
276-- Transformation Folds
277------------------------------------------------------------------------------
279-- | Right fold to a streaming monad.
280--
281-- > foldrS S.cons S.nil === id
282--
283-- 'foldrS' can be used to perform stateless stream to stream transformations
284-- like map and filter in general. It can be coupled with a scan to perform
285-- stateful transformations. However, note that the custom map and filter
286-- routines can be much more efficient than this due to better stream fusion.
287--
288-- >>> S.toList $ S.foldrS S.cons S.nil $ S.fromList [1..5]
289-- > [1,2,3,4,5]
290--
291-- Find if any element in the stream is 'True':
292--
293-- >>> S.toList $ S.foldrS (\x xs -> if odd x then return True else xs) (return False) $ (S.fromList (2:4:5:undefined) :: SerialT IO Int)
294-- > [True]
295--
296-- Map (+2) on odd elements and filter out the even elements:
297--
298-- >>> S.toList $ S.foldrS (\x xs -> if odd x then (x + 2) `S.cons` xs else xs) S.nil $ (S.fromList [1..5] :: SerialT IO Int)
299-- > [3,5,7]
300--
301-- 'foldrM' can also be represented in terms of 'foldrS', however, the former
302-- is much more efficient:
303--
304-- > foldrM f z s = runIdentityT $ foldrS (\x xs -> lift $ f x (runIdentityT xs)) (lift z) s
305--
306-- /Internal/
307{-# INLINE foldrS #-}
308foldrS :: IsStream t => (a -> t m b -> t m b) -> t m b -> t m a -> t m b
309foldrS = K.foldrS
311-- | Right fold to a transformer monad. This is the most general right fold
312-- function. 'foldrS' is a special case of 'foldrT', however 'foldrS'
313-- implementation can be more efficient:
314--
315-- > foldrS = foldrT
316-- > foldrM f z s = runIdentityT $ foldrT (\x xs -> lift $ f x (runIdentityT xs)) (lift z) s
317--
318-- 'foldrT' can be used to translate streamly streams to other transformer
319-- monads e.g. to a different streaming type.
320--
321-- /Internal/
322{-# INLINE foldrT #-}
323foldrT :: (IsStream t, Monad m, Monad (s m), MonadTrans s)
324 => (a -> s m b -> s m b) -> s m b -> t m a -> s m b
325foldrT f z s = S.foldrT f z (toStreamS s)
327------------------------------------------------------------------------------
328-- Transformation by Mapping
329------------------------------------------------------------------------------
331-- |
332-- @
333-- mapM f = sequence . map f
334-- @
335--
336-- Apply a monadic function to each element of the stream and replace it with
337-- the output of the resulting action.
338--
339-- @
340-- > drain $ S.mapM putStr $ S.fromList ["a", "b", "c"]
341-- abc
342--
343-- drain $ S.replicateM 10 (return 1)
344-- & (serially . S.mapM (\\x -> threadDelay 1000000 >> print x))
345--
346-- drain $ S.replicateM 10 (return 1)
347-- & (asyncly . S.mapM (\\x -> threadDelay 1000000 >> print x))
348-- @
349--
350-- /Concurrent (do not use with 'parallely' on infinite streams)/
351--
352-- @since 0.1.0
353{-# INLINE_EARLY mapM #-}
354mapM :: (IsStream t, MonadAsync m) => (a -> m b) -> t m a -> t m b
355mapM = K.mapM
357{-# RULES "mapM serial" mapM = mapMSerial #-}
358{-# INLINE mapMSerial #-}
359mapMSerial :: Monad m => (a -> m b) -> SerialT m a -> SerialT m b
360mapMSerial = Serial.mapM
362-- |
363-- @
364-- sequence = mapM id
365-- @
366--
367-- Replace the elements of a stream of monadic actions with the outputs of
368-- those actions.
369--
370-- @
371-- > drain $ S.sequence $ S.fromList [putStr "a", putStr "b", putStrLn "c"]
372-- abc
373--
374-- drain $ S.replicateM 10 (return $ threadDelay 1000000 >> print 1)
375-- & (serially . S.sequence)
376--
377-- drain $ S.replicateM 10 (return $ threadDelay 1000000 >> print 1)
378-- & (asyncly . S.sequence)
379-- @
380--
381-- /Concurrent (do not use with 'parallely' on infinite streams)/
382--
383-- @since 0.1.0
384{-# INLINE sequence #-}
385sequence :: (IsStream t, MonadAsync m) => t m (m a) -> t m a
386sequence m = fromStreamS $ S.sequence (toStreamS m)
388------------------------------------------------------------------------------
389-- Mapping side effects
390------------------------------------------------------------------------------
392-- | Tap the data flowing through a stream into a 'Fold'. For example, you may
393-- add a tap to log the contents flowing through the stream. The fold is used
394-- only for effects, its result is discarded.
395--
396-- @
397-- Fold m a b
398-- |
399-- -----stream m a ---------------stream m a-----
400--
401-- @
402--
403-- @
404-- > S.drain $ S.tap (FL.drainBy print) (S.enumerateFromTo 1 2)
405-- 1
406-- 2
407-- @
408--
409-- Compare with 'trace'.
410--
411-- @since 0.7.0
412{-# INLINE tap #-}
413tap :: (IsStream t, Monad m) => FL.Fold m a b -> t m a -> t m a
414tap f xs = D.fromStreamD $ D.tap f (D.toStreamD xs)
416-- XXX Remove this. It can be expressed in terms of Fold.sampleFromThen.
417--
418-- | @tapOffsetEvery offset n@ taps every @n@th element in the stream
419-- starting at @offset@. @offset@ can be between @0@ and @n - 1@. Offset 0
420-- means start at the first element in the stream. If the offset is outside
421-- this range then @offset `mod` n@ is used as offset.
422--
423-- @
424-- >>> S.drain $ S.tapOffsetEvery 0 2 (FL.rmapM print FL.toList) $ S.enumerateFromTo 0 10
425-- > [0,2,4,6,8,10]
426-- @
427--
428-- /Internal/
429--
430{-# INLINE tapOffsetEvery #-}
431tapOffsetEvery :: (IsStream t, Monad m)
432 => Int -> Int -> FL.Fold m a b -> t m a -> t m a
433tapOffsetEvery offset n f xs =
434 D.fromStreamD $ D.tapOffsetEvery offset n f (D.toStreamD xs)
436-- | Redirect a copy of the stream to a supplied fold and run it concurrently
437-- in an independent thread. The fold may buffer some elements. The buffer size
438-- is determined by the prevailing 'maxBuffer' setting.
439--
440-- @
441-- Stream m a -> m b
442-- |
443-- -----stream m a ---------------stream m a-----
444--
445-- @
446--
447-- @
448-- > S.drain $ S.tapAsync (S.mapM_ print) (S.enumerateFromTo 1 2)
449-- 1
450-- 2
451-- @
452--
453-- Exceptions from the concurrently running fold are propagated to the current
454-- computation. Note that, because of buffering in the fold, exceptions may be
455-- delayed and may not correspond to the current element being processed in the
456-- parent stream, but we guarantee that before the parent stream stops the tap
457-- finishes and all exceptions from it are drained.
458--
459--
460-- Compare with 'tap'.
461--
462-- /Internal/
463{-# INLINE tapAsync #-}
464tapAsync :: (IsStream t, MonadAsync m) => FL.Fold m a b -> t m a -> t m a
465tapAsync f xs = D.fromStreamD $ Par.tapAsyncF f (D.toStreamD xs)
467-- | @pollCounts predicate transform fold stream@ counts those elements in the
468-- stream that pass the @predicate@. The resulting count stream is sent to
469-- another thread which transforms it using @transform@ and then folds it using
470-- @fold@. The thread is automatically cleaned up if the stream stops or
471-- aborts due to exception.
472--
473-- For example, to print the count of elements processed every second:
474--
475-- @
476-- > S.drain $ S.pollCounts (const True) (S.rollingMap (-) . S.delayPost 1) (FL.drainBy print)
477-- $ S.enumerateFrom 0
478-- @
479--
480-- Note: This may not work correctly on 32-bit machines.
481--
482-- /Internal/
483--
484{-# INLINE pollCounts #-}
485pollCounts ::
486 (IsStream t, MonadAsync m)
487 => (a -> Bool)
488 -> (t m Int -> t m Int)
489 -> Fold m Int b
490 -> t m a
491 -> t m a
492pollCounts predicate transf f xs =
493 D.fromStreamD
494 $ D.pollCounts predicate (D.toStreamD . transf . D.fromStreamD) f
495 $ D.toStreamD xs
497-- | Calls the supplied function with the number of elements consumed
498-- every @n@ seconds. The given function is run in a separate thread
499-- until the end of the stream. In case there is an exception in the
500-- stream the thread is killed during the next major GC.
501--
502-- Note: The action is not guaranteed to run if the main thread exits.
503--
504-- @
505-- > delay n = threadDelay (round $ n * 1000000) >> return n
506-- > S.drain $ S.tapRate 2 (\\n -> print $ show n ++ " elements processed") (delay 1 S.|: delay 0.5 S.|: delay 0.5 S.|: S.nil)
507-- 2 elements processed
508-- 1 elements processed
509-- @
510--
511-- Note: This may not work correctly on 32-bit machines.
512--
513-- /Internal/
514{-# INLINE tapRate #-}
515tapRate ::
516 (IsStream t, MonadAsync m, MonadCatch m)
517 => Double
518 -> (Int -> m b)
519 -> t m a
520 -> t m a
521tapRate n f xs = D.fromStreamD $ D.tapRate n f $ D.toStreamD xs
523-- | Apply a monadic function to each element flowing through the stream and
524-- discard the results.
525--
526-- @
527-- > S.drain $ S.trace print (S.enumerateFromTo 1 2)
528-- 1
529-- 2
530-- @
531--
532-- Compare with 'tap'.
533--
534-- @since 0.7.0
535{-# INLINE trace #-}
536trace :: (IsStream t, MonadAsync m) => (a -> m b) -> t m a -> t m a
537trace f = mapM (\x -> void (f x) >> return x)
539-- | Perform a side effect before yielding each element of the stream and
540-- discard the results.
541--
542-- @
543-- > S.drain $ S.trace_ (print "got here") (S.enumerateFromTo 1 2)
544-- "got here"
545-- "got here"
546-- @
547--
548-- Same as 'interspersePrefix_' but always serial.
549--
550-- See also: 'trace'
551--
552-- /Internal/
553{-# INLINE trace_ #-}
554trace_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
555trace_ eff = Serial.mapM (\x -> eff >> return x)
557------------------------------------------------------------------------------
558-- Scanning with a Fold
559------------------------------------------------------------------------------
561-- | Scan a stream using the given monadic fold.
562--
563-- @since 0.7.0
564{-# INLINE scan #-}
565scan :: (IsStream t, Monad m) => Fold m a b -> t m a -> t m b
566scan = P.scanOnce
568-- | Postscan a stream using the given monadic fold.
569--
570-- @since 0.7.0
571{-# INLINE postscan #-}
572postscan :: (IsStream t, Monad m) => Fold m a b -> t m a -> t m b
573postscan = P.postscanOnce
575------------------------------------------------------------------------------
576-- Scanning - Transformation by Folding
577------------------------------------------------------------------------------
579-- XXX It may be useful to have a version of scan where we can keep the
580-- accumulator independent of the value emitted. So that we do not necessarily
581-- have to keep a value in the accumulator which we are not using. We can pass
582-- an extraction function that will take the accumulator and the current value
583-- of the element and emit the next value in the stream. That will also make it
584-- possible to modify the accumulator after using it. In fact, the step function
585-- can return new accumulator and the value to be emitted. The signature would
586-- be more like mapAccumL. Or we can change the signature of scanx to
587-- accommodate this.
588--
589-- | Strict left scan with an extraction function. Like 'scanl'', but applies a
590-- user supplied extraction function (the third argument) at each step. This is
591-- designed to work with the @foldl@ library. The suffix @x@ is a mnemonic for
592-- extraction.
593--
594-- /Since 0.2.0/
595--
596-- /Since: 0.7.0 (Monad m constraint)/
597{-# DEPRECATED scanx "Please use scanl followed by map instead." #-}
598{-# INLINE scanx #-}
599scanx :: (IsStream t, Monad m) => (x -> a -> x) -> x -> (x -> b) -> t m a -> t m b
600scanx = P.scanlx'
602-- XXX this needs to be concurrent
603-- XXX because of the use of D.cons for appending, scanlM' has quadratic
604-- complexity when iterated over a stream. We should use StreamK style scanlM'
605-- for linear performance on iteration.
606--
607-- | Like 'scanl'' but with a monadic step function and a monadic seed.
608--
609-- /Since: 0.4.0/
610--
611-- /Since: 0.8.0 (signature change)/
612{-# INLINE scanlM' #-}
613scanlM' :: (IsStream t, Monad m) => (b -> a -> m b) -> m b -> t m a -> t m b
614scanlM' step begin m = fromStreamD $ D.scanlM' step begin $ toStreamD m
616-- XXX because of the use of D.cons for appending, scanl' has quadratic
617-- complexity when iterated over a stream. We should use StreamK style scanlM'
618-- for linear performance on iteration.
620-- | Strict left scan. Like 'map', 'scanl'' too is a one to one transformation,
621-- however it adds an extra element.
622--
623-- @
624-- > S.toList $ S.scanl' (+) 0 $ fromList [1,2,3,4]
625-- [0,1,3,6,10]
626-- @
627--
628-- @
629-- > S.toList $ S.scanl' (flip (:)) [] $ S.fromList [1,2,3,4]
630-- [[],[1],[2,1],[3,2,1],[4,3,2,1]]
631-- @
632--
633-- The output of 'scanl'' is the initial value of the accumulator followed by
634-- all the intermediate steps and the final result of 'foldl''.
635--
636-- By streaming the accumulated state after each fold step, we can share the
637-- state across multiple stages of stream composition. Each stage can modify or
638-- extend the state, do some processing with it and emit it for the next stage,
639-- thus modularizing the stream processing. This can be useful in
640-- stateful or event-driven programming.
641--
642-- Consider the following monolithic example, computing the sum and the product
643-- of the elements in a stream in one go using a @foldl'@:
644--
645-- @
646-- > S.foldl' (\\(s, p) x -> (s + x, p * x)) (0,1) $ S.fromList \[1,2,3,4]
647-- (10,24)
648-- @
649--
650-- Using @scanl'@ we can make it modular by computing the sum in the first
651-- stage and passing it down to the next stage for computing the product:
652--
653-- @
654-- > S.foldl' (\\(_, p) (s, x) -> (s, p * x)) (0,1)
655-- $ S.scanl' (\\(s, _) x -> (s + x, x)) (0,1)
656-- $ S.fromList \[1,2,3,4]
657-- (10,24)
658-- @
659--
660-- IMPORTANT: 'scanl'' evaluates the accumulator to WHNF. To avoid building
661-- lazy expressions inside the accumulator, it is recommended that a strict
662-- data structure is used for accumulator.
663--
664-- See also: 'usingStateT'
665--
666-- @since 0.2.0
667{-# INLINE scanl' #-}
668scanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
669scanl' step z m = fromStreamS $ S.scanl' step z $ toStreamS m
671-- | Like 'scanl'' but does not stream the initial value of the accumulator.
672--
673-- > postscanl' f z xs = S.drop 1 $ S.scanl' f z xs
674--
675-- @since 0.7.0
676{-# INLINE postscanl' #-}
677postscanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
678postscanl' step z m = fromStreamD $ D.postscanl' step z $ toStreamD m
680-- XXX prescanl does not sound very useful, enable only if there is a
681-- compelling use case.
682--
683-- | Like scanl' but does not stream the final value of the accumulator.
684--
685-- /Internal/
686{-# INLINE prescanl' #-}
687prescanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
688prescanl' step z m = fromStreamD $ D.prescanl' step z $ toStreamD m
690-- XXX this needs to be concurrent
691-- | Like prescanl' but with a monadic step function and a monadic seed.
692--
693-- /Internal/
694{-# INLINE prescanlM' #-}
695prescanlM' :: (IsStream t, Monad m) => (b -> a -> m b) -> m b -> t m a -> t m b
696prescanlM' step z m = fromStreamD $ D.prescanlM' step z $ toStreamD m
698-- XXX this needs to be concurrent
699-- | Like 'scanl1'' but with a monadic step function.
700--
701-- @since 0.6.0
702{-# INLINE scanl1M' #-}
703scanl1M' :: (IsStream t, Monad m) => (a -> a -> m a) -> t m a -> t m a
704scanl1M' step m = fromStreamD $ D.scanl1M' step $ toStreamD m
706-- | Like 'scanl'' but for a non-empty stream. The first element of the stream
707-- is used as the initial value of the accumulator. Does nothing if the stream
708-- is empty.
709--
710-- @
711-- > S.toList $ S.scanl1 (+) $ fromList [1,2,3,4]
712-- [1,3,6,10]
713-- @
714--
715-- @since 0.6.0
716{-# INLINE scanl1' #-}
717scanl1' :: (IsStream t, Monad m) => (a -> a -> a) -> t m a -> t m a
718scanl1' step m = fromStreamD $ D.scanl1' step $ toStreamD m
720------------------------------------------------------------------------------
721-- Filtering
722------------------------------------------------------------------------------
724-- | Modify a @t m a -> t m a@ stream transformation that accepts a predicate
725-- @(a -> b)@ to accept @((s, a) -> b)@ instead, provided a transformation @t m
726-- a -> t m (s, a)@. Convenient to filter with index or time.
727--
728-- @
729-- filterWithIndex = with indexed filter
730-- filterWithAbsTime = with timestamped filter
731-- filterWithRelTime = with timeIndexed filter
732-- @
733--
734-- /Internal/
735{-# INLINE with #-}
736with :: forall (t :: (Type -> Type) -> Type -> Type) m a b s. Functor (t m) =>
737 (t m a -> t m (s, a))
738 -> (((s, a) -> b) -> t m (s, a) -> t m (s, a))
739 -> (((s, a) -> b) -> t m a -> t m a)
740with f comb g = fmap snd . comb g . f
742-- | Include only those elements that pass a predicate.
743--
744-- @since 0.1.0
745{-# INLINE filter #-}
746#if __GLASGOW_HASKELL__ != 802
747-- GHC 8.2.2 crashes with this code, when used with "stack"
748filter :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m a
749filter p m = fromStreamS $ S.filter p $ toStreamS m
750#else
751filter :: IsStream t => (a -> Bool) -> t m a -> t m a
752filter = K.filter
753#endif
755-- | Same as 'filter' but with a monadic predicate.
756--
757-- @since 0.4.0
758{-# INLINE filterM #-}
759filterM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
760filterM p m = fromStreamD $ D.filterM p $ toStreamD m
762-- | Drop repeated elements that are adjacent to each other using the supplied
763-- comparison function.
764--
765-- @uniq = uniqBy (==)
766--
767-- To strip duplicate path separators:
768--
769-- @
770-- f x y = x == '/' && x == y
771-- Stream.toList $ Stream.uniqBy f $ Stream.fromList "//a//b"
772-- "/a/b"
773-- @
774--
775-- Space: @O(1)@
776--
777-- See also: 'nubBy'.
778--
779-- /Internal/
780--
781{-# INLINE uniqBy #-}
782uniqBy :: (IsStream t, Monad m, Functor (t m)) =>
783 (a -> a -> Bool) -> t m a -> t m a
784uniqBy eq =
785 catMaybes . rollingMap (\x y -> if x `eq` y then Nothing else Just y)
787-- | Drop repeated elements that are adjacent to each other.
788--
789-- @since 0.6.0
790{-# INLINE uniq #-}
791uniq :: (Eq a, IsStream t, Monad m) => t m a -> t m a
792uniq = fromStreamD . D.uniq . toStreamD
794-- | Strip all leading and trailing occurrences of an element passing a
795-- predicate and make all other consecutive occurrences uniq.
796--
797-- @
798-- prune p = dropWhileAround p $ uniqBy (x y -> p x && p y)
799-- @
800--
801-- >>> Stream.pruneBy isSpace (Stream.fromList " hello world! ")
802-- "hello world!"
803--
804-- Space: @O(1)@
805--
806-- /Unimplemented/
807{-# INLINE prune #-}
808prune ::
809 -- (IsStream t, Monad m, Eq a) =>
810 (a -> Bool) -> t m a -> t m a
811prune = error "Not implemented yet!"
813-- Possible implementation:
814-- @repeated =
815-- Stream.catMaybes . Stream.parseMany (Parser.groupBy (==) Fold.repeated)@
816--
817-- 'Fold.repeated' should return 'Just' when repeated, and 'Nothing' for a
818-- single element.
819--
820-- | Emit only repeated elements, once.
821--
822-- /Unimplemented/
823repeated :: -- (IsStream t, Monad m, Eq a) =>
824 t m a -> t m a
825repeated = undefined
827-- We can have more efficient implementations for nubOrd and nubInt by using
828-- Set and IntSet to find/remove duplication. For Hashable we can use a
829-- hashmap. Use rewrite rules to specialize to more efficient impls.
830--
831-- | Drop repeated elements anywhere in the stream.
832--
833-- /Caution: not scalable for infinite streams/
834--
835-- /See also: nubWindowBy/
836--
837-- /Unimplemented/
838--
839{-# INLINE nubBy #-}
840nubBy :: -- (IsStream t, Monad m) =>
841 (a -> a -> Bool) -> t m a -> t m a
842nubBy = undefined -- fromStreamD . D.nubBy . toStreamD
844-- | Drop repeated elements within the specified tumbling window in the stream.
845--
846-- @nubBy = nubWindowBy maxBound@
847--
848-- /Unimplemented/
849--
850{-# INLINE nubWindowBy #-}
851nubWindowBy :: -- (IsStream t, Monad m) =>
852 Int -> (a -> a -> Bool) -> t m a -> t m a
853nubWindowBy = undefined -- fromStreamD . D.nubWithinBy . toStreamD
855-- | Deletes the first occurrence of the element in the stream that satisfies
856-- the given equality predicate.
857--
858-- @
859-- > S.toList $ S.deleteBy (==) 3 $ S.fromList [1,3,3,5]
860-- [1,3,5]
861-- @
862--
863-- @since 0.6.0
864{-# INLINE deleteBy #-}
865deleteBy :: (IsStream t, Monad m) => (a -> a -> Bool) -> a -> t m a -> t m a
866deleteBy cmp x m = fromStreamS $ S.deleteBy cmp x (toStreamS m)
868------------------------------------------------------------------------------
869-- Lossy Buffering
870------------------------------------------------------------------------------
872-- XXX We could use 'maxBuffer Block/Drop/Rotate/Sample' instead. However we
873-- may want to have the evaluation rate independent of the sampling rate. To
874-- support that we can decouple evaluation and sampling in independent stages.
875-- The sampling stage would strictly evaluate and sample, the evaluation stage
876-- would control the evaluation rate.
878-- | Evaluate the input stream continuously and keep only the oldest @n@
879-- elements in the buffer, discard the new ones when the buffer is full. When
880-- the output stream is evaluated it consumes the values from the buffer in a
881-- FIFO manner.
882--
883-- /Unimplemented/
884--
885{-# INLINE sampleOld #-}
886sampleOld :: -- (IsStream t, Monad m) =>
887 Int -> t m a -> t m a
888sampleOld = undefined
890-- | Evaluate the input stream continuously and keep only the latest @n@
891-- elements in a ring buffer, keep discarding the older ones to make space for
892-- the new ones. When the output stream is evaluated it consumes the values
893-- from the buffer in a FIFO manner.
894--
895-- /Unimplemented/
896--
897{-# INLINE sampleNew #-}
898sampleNew :: -- (IsStream t, Monad m) =>
899 Int -> t m a -> t m a
900sampleNew = undefined
902-- | Like 'sampleNew' but samples at uniform intervals to match the consumer
903-- rate. Note that 'sampleNew' leads to non-uniform sampling depending on the
904-- consumer pattern.
905--
906-- /Unimplemented/
907--
908{-# INLINE sampleRate #-}
909sampleRate :: -- (IsStream t, Monad m) =>
910 Double -> t m a -> t m a
911sampleRate = undefined
913------------------------------------------------------------------------------
914-- Trimming
915------------------------------------------------------------------------------
917-- | Same as 'takeWhile' but with a monadic predicate.
918--
919-- @since 0.4.0
920{-# INLINE takeWhileM #-}
921takeWhileM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
922takeWhileM p m = fromStreamD $ D.takeWhileM p $ toStreamD m
924-- See the lastN fold for impl hints. Use a Data.Array based ring buffer.
925--
926-- takeEnd n = Stream.concatM . fmap Array.toStream . fold Fold.lastN
927--
928-- | Take @n@ elements at the end of the stream.
929--
930-- O(n) space, where n is the number elements taken.
931--
932-- /Unimplemented/
933{-# INLINE takeEnd #-}
934takeEnd :: -- (IsStream t, Monad m) =>
935 Int -> t m a -> t m a
936takeEnd = undefined -- fromStreamD $ D.takeEnd n $ toStreamD m
938-- | Take time interval @i@ seconds at the end of the stream.
939--
940-- O(n) space, where n is the number elements taken.
941--
942-- /Unimplemented/
943{-# INLINE takeEndInterval #-}
944takeEndInterval :: -- (IsStream t, Monad m) =>
945 Double -> t m a -> t m a
946takeEndInterval = undefined -- fromStreamD $ D.takeEnd n $ toStreamD m
948-- | Take all consecutive elements at the end of the stream for which the
949-- predicate is true.
950--
951-- O(n) space, where n is the number elements taken.
952--
953-- /Unimplemented/
954{-# INLINE takeWhileEnd #-}
955takeWhileEnd :: -- (IsStream t, Monad m) =>
956 (a -> Bool) -> t m a -> t m a
957takeWhileEnd = undefined -- fromStreamD $ D.takeWhileEnd n $ toStreamD m
959-- | Like 'takeWhile' and 'takeWhileEnd' combined.
960--
961-- O(n) space, where n is the number elements taken from the end.
962--
963-- /Unimplemented/
964{-# INLINE takeWhileAround #-}
965takeWhileAround :: -- (IsStream t, Monad m) =>
966 (a -> Bool) -> t m a -> t m a
967takeWhileAround = undefined -- fromStreamD $ D.takeWhileAround n $ toStreamD m
969-- | @takeByTime duration@ yields stream elements upto specified time
970-- @duration@. The duration starts when the stream is evaluated for the first
971-- time, before the first element is yielded. The time duration is checked
972-- before generating each element, if the duration has expired the stream
973-- stops.
974--
975-- The total time taken in executing the stream is guaranteed to be /at least/
976-- @duration@, however, because the duration is checked before generating an
977-- element, the upper bound is indeterminate and depends on the time taken in
978-- generating and processing the last element.
979--
980-- No element is yielded if the duration is zero. At least one element is
981-- yielded if the duration is non-zero.
982--
983-- /Internal/
984--
985{-# INLINE takeByTime #-}
986takeByTime ::(MonadIO m, IsStream t, TimeUnit64 d) => d -> t m a -> t m a
987takeByTime d = fromStreamD . D.takeByTime d . toStreamD
989-- | Drop elements in the stream as long as the predicate succeeds and then
990-- take the rest of the stream.
991--
992-- @since 0.1.0
993{-# INLINE dropWhile #-}
994dropWhile :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m a
995dropWhile p m = fromStreamS $ S.dropWhile p $ toStreamS m
997-- | Same as 'dropWhile' but with a monadic predicate.
998--
999-- @since 0.4.0
1000{-# INLINE dropWhileM #-}
1001dropWhileM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
1002dropWhileM p m = fromStreamD $ D.dropWhileM p $ toStreamD m
1004-- | @dropByTime duration@ drops stream elements until specified @duration@ has
1005-- passed. The duration begins when the stream is evaluated for the first
1006-- time. The time duration is checked /after/ generating a stream element, the
1007-- element is yielded if the duration has expired otherwise it is dropped.
1009-- The time elapsed before starting to generate the first element is /at most/
1010-- @duration@, however, because the duration expiry is checked after the
1011-- element is generated, the lower bound is indeterminate and depends on the
1012-- time taken in generating an element.
1014-- All elements are yielded if the duration is zero.
1016-- /Internal/
1018{-# INLINE dropByTime #-}
1019dropByTime ::(MonadIO m, IsStream t, TimeUnit64 d) => d -> t m a -> t m a
1020dropByTime d = fromStreamD . D.dropByTime d . toStreamD
1022-- | Drop @n@ elements at the end of the stream.
1024-- O(n) space, where n is the number elements dropped.
1026-- /Unimplemented/
1027{-# INLINE dropEnd #-}
1028dropEnd :: -- (IsStream t, Monad m) =>
1029 Int -> t m a -> t m a
1030dropEnd = undefined -- fromStreamD $ D.dropEnd n $ toStreamD m
1032-- | Drop time interval @i@ seconds at the end of the stream.
1034-- O(n) space, where n is the number elements dropped.
1036-- /Unimplemented/
1037{-# INLINE dropEndInterval #-}
1038dropEndInterval :: -- (IsStream t, Monad m) =>
1039 Int -> t m a -> t m a
1040dropEndInterval = undefined
1042-- | Drop all consecutive elements at the end of the stream for which the
1043-- predicate is true.
1045-- O(n) space, where n is the number elements dropped.
1047-- /Unimplemented/
1048{-# INLINE dropWhileEnd #-}
1049dropWhileEnd :: -- (IsStream t, Monad m) =>
1050 (a -> Bool) -> t m a -> t m a
1051dropWhileEnd = undefined -- fromStreamD $ D.dropWhileEnd n $ toStreamD m
1053-- | Like 'dropWhile' and 'dropWhileEnd' combined.
1055-- O(n) space, where n is the number elements dropped from the end.
1057-- /Unimplemented/
1058{-# INLINE dropWhileAround #-}
1059dropWhileAround :: -- (IsStream t, Monad m) =>
1060 (a -> Bool) -> t m a -> t m a
1061dropWhileAround = undefined -- fromStreamD $ D.dropWhileAround n $ toStreamD m
1063------------------------------------------------------------------------------
1064-- Inserting Elements
1065------------------------------------------------------------------------------
1067-- | @insertBy cmp elem stream@ inserts @elem@ before the first element in
1068-- @stream@ that is less than @elem@ when compared using @cmp@.
1070-- @
1071-- insertBy cmp x = 'mergeBy' cmp ('yield' x)
1072-- @
1074-- @
1075-- > S.toList $ S.insertBy compare 2 $ S.fromList [1,3,5]
1076-- [1,2,3,5]
1077-- @
1079-- @since 0.6.0
1080{-# INLINE insertBy #-}
1081insertBy ::
1082 (IsStream t, Monad m) => (a -> a -> Ordering) -> a -> t m a -> t m a
1083insertBy cmp x m = fromStreamS $ S.insertBy cmp x (toStreamS m)
1085-- | Insert a pure value between successive elements of a stream.
1087-- @
1088-- > S.toList $ S.intersperse ',' $ S.fromList "hello"
1089-- "h,e,l,l,o"
1090-- @
1092-- @since 0.7.0
1093{-# INLINE intersperse #-}
1094intersperse :: (IsStream t, MonadAsync m) => a -> t m a -> t m a
1095intersperse a = fromStreamS . S.intersperse a . toStreamS
1097-- | Insert a side effect before consuming an element of a stream except the
1098-- first one.
1100-- @
1101-- >>> S.drain $ S.trace putChar $ S.intersperseM_ (putChar '.') $ S.fromList "hello"
1102-- > h.e.l.l.o
1103-- @
1105-- /Internal/
1106{-# INLINE intersperseM_ #-}
1107intersperseM_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
1108intersperseM_ m = fromStreamD . D.intersperseM_ m . toStreamD
1110-- | Intersperse a monadic action into the input stream after every @n@
1111-- elements.
1113-- @
1114-- > S.toList $ S.intersperseBySpan 2 (return ',') $ S.fromList "hello"
1115-- "he,ll,o"
1116-- @
1118-- /Unimplemented/
1119{-# INLINE intersperseBySpan #-}
1120intersperseBySpan :: -- IsStream t =>
1121 Int -> m a -> t m a -> t m a
1122intersperseBySpan _n _f _xs = undefined
1124-- | Insert an effect and its output after consuming an element of a stream.
1126-- @
1127-- >>> S.toList $ S.trace putChar $ S.intersperseSuffix (putChar '.' >> return ',') $ S.fromList "hello"
1128-- > h.,e.,l.,l.,o.,"h,e,l,l,o,"
1129-- @
1131-- /Internal/
1132{-# INLINE intersperseSuffix #-}
1133intersperseSuffix :: (IsStream t, MonadAsync m) => m a -> t m a -> t m a
1134intersperseSuffix m = fromStreamD . D.intersperseSuffix m . toStreamD
1136-- | Insert a side effect after consuming an element of a stream.
1138-- @
1139-- > S.mapM_ putChar $ S.intersperseSuffix_ (threadDelay 1000000) $ S.fromList "hello"
1140-- @
1142-- /Internal/
1144{-# INLINE intersperseSuffix_ #-}
1145intersperseSuffix_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
1146intersperseSuffix_ m = fromStreamD . D.intersperseSuffix_ m . toStreamD
1148-- XXX Use an offset argument, like tapOffsetEvery
1150-- | Like 'intersperseSuffix' but intersperses an effectful action into the
1151-- input stream after every @n@ elements and after the last element.
1153-- @
1154-- > S.toList $ S.intersperseSuffixBySpan 2 (return ',') $ S.fromList "hello"
1155-- "he,ll,o,"
1156-- @
1158-- /Internal/
1160{-# INLINE intersperseSuffixBySpan #-}
1161intersperseSuffixBySpan :: (IsStream t, MonadAsync m)
1162 => Int -> m a -> t m a -> t m a
1163intersperseSuffixBySpan n eff =
1164 fromStreamD . D.intersperseSuffixBySpan n eff . toStreamD
1166-- | Insert a side effect before consuming an element of a stream.
1168-- @
1169-- >>> S.toList $ S.trace putChar $ S.interspersePrefix_ (putChar '.' >> return ',') $ S.fromList "hello"
1170-- > .h.e.l.l.o"hello"
1171-- @
1173-- Same as 'trace_' but may be concurrent.
1175-- /Concurrent/
1177-- /Internal/
1179{-# INLINE interspersePrefix_ #-}
1180interspersePrefix_ :: (IsStream t, MonadAsync m) => m b -> t m a -> t m a
1181interspersePrefix_ m = mapM (\x -> void m >> return x)
1183------------------------------------------------------------------------------
1184-- Inserting Time
1185------------------------------------------------------------------------------
1187-- Note: delay must be serial.
1189-- | Introduce a delay of specified seconds before consuming an element of the
1190-- stream except the first one.
1192-- @
1193-- >>> S.mapM_ print $ S.timestamped $ S.delay 1 $ S.enumerateFromTo 1 3
1194-- > (AbsTime (TimeSpec {sec = 2502706, nsec = 751137000}),1)
1195-- > (AbsTime (TimeSpec {sec = 2502707, nsec = 743535000}),2)
1196-- > (AbsTime (TimeSpec {sec = 2502708, nsec = 749758000}),3)
1197-- @
1199-- /Internal/
1201{-# INLINE delay #-}
1202delay :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
1203delay n = intersperseM_ $ liftIO $ threadDelay $ round $ n * 1000000
1205-- Note: delay must be serial.
1207-- | Introduce a delay of specified seconds after consuming an element of a
1208-- stream.
1210-- @
1211-- >>> S.mapM_ print $ S.timestamped $ S.delayPost 1 $ S.enumerateFromTo 1 3
1212-- > (AbsTime (TimeSpec {sec = 2502826, nsec = 119030000}),1)
1213-- > (AbsTime (TimeSpec {sec = 2502827, nsec = 111393000}),2)
1214-- > (AbsTime (TimeSpec {sec = 2502828, nsec = 112221000}),3)
1215-- @
1217-- /Internal/
1219{-# INLINE delayPost #-}
1220delayPost :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
1221delayPost n = intersperseSuffix_ $ liftIO $ threadDelay $ round $ n * 1000000
1223-- Note: delay must be serial, that's why 'trace_' is used.
1225-- | Introduce a delay of specified seconds before consuming an element of a
1226-- stream.
1228-- @
1229-- >>> S.mapM_ print $ S.timestamped $ S.delayPre 1 $ S.enumerateFromTo 1 3
1230-- > (AbsTime (TimeSpec {sec = 2502207, nsec = 533177000}),1)
1231-- > (AbsTime (TimeSpec {sec = 2502208, nsec = 530859000}),2)
1232-- > (AbsTime (TimeSpec {sec = 2502209, nsec = 531619000}),3)
1233-- @
1235-- /Internal/
1237{-# INLINE delayPre #-}
1238delayPre :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
1239delayPre n = trace_ $ liftIO $ threadDelay $ round $ n * 1000000
1241------------------------------------------------------------------------------
1242-- Reorder in sequence
1243------------------------------------------------------------------------------
1245-- | Buffer until the next element in sequence arrives. The function argument
1246-- determines the difference in sequence numbers. This could be useful in
1247-- implementing sequenced streams, for example, TCP reassembly.
1249-- /Unimplemented/
1251{-# INLINE reassembleBy #-}
1252reassembleBy
1253 :: -- (IsStream t, Monad m) =>
1254 Fold m a b
1255 -> (a -> a -> Int)
1256 -> t m a
1257 -> t m b
1258reassembleBy = undefined
1260------------------------------------------------------------------------------
1261-- Position Indexing
1262------------------------------------------------------------------------------
1264-- |
1265-- > indexed = S.postscanl' (\(i, _) x -> (i + 1, x)) (-1,undefined)
1266-- > indexed = S.zipWith (,) (S.enumerateFrom 0)
1268-- Pair each element in a stream with its index, starting from index 0.
1270-- @
1271-- > S.toList $ S.indexed $ S.fromList "hello"
1272-- [(0,'h'),(1,'e'),(2,'l'),(3,'l'),(4,'o')]
1273-- @
1275-- @since 0.6.0
1276{-# INLINE indexed #-}
1277indexed :: (IsStream t, Monad m) => t m a -> t m (Int, a)
1278indexed = fromStreamD . D.indexed . toStreamD
1280-- |
1281-- > indexedR n = S.postscanl' (\(i, _) x -> (i - 1, x)) (n + 1,undefined)
1282-- > indexedR n = S.zipWith (,) (S.enumerateFromThen n (n - 1))
1284-- Pair each element in a stream with its index, starting from the
1285-- given index @n@ and counting down.
1287-- @
1288-- > S.toList $ S.indexedR 10 $ S.fromList "hello"
1289-- [(10,'h'),(9,'e'),(8,'l'),(7,'l'),(6,'o')]
1290-- @
1292-- @since 0.6.0
1293{-# INLINE indexedR #-}
1294indexedR :: (IsStream t, Monad m) => Int -> t m a -> t m (Int, a)
1295indexedR n = fromStreamD . D.indexedR n . toStreamD
1297-------------------------------------------------------------------------------
1298-- Time Indexing
1299-------------------------------------------------------------------------------
1301-- Note: The timestamp stream must be the second stream in the zip so that the
1302-- timestamp is generated after generating the stream element and not before.
1303-- If we do not do that then the following example will generate the same
1304-- timestamp for first two elements:
1306-- S.mapM_ print $ S.timestamped $ S.delay $ S.enumerateFromTo 1 3
1308-- | Pair each element in a stream with an absolute timestamp, using a clock of
1309-- specified granularity. The timestamp is generated just before the element
1310-- is consumed.
1312-- @
1313-- >>> S.mapM_ print $ S.timestampWith 0.01 $ S.delay 1 $ S.enumerateFromTo 1 3
1314-- @
1316-- /Internal/
1318{-# INLINE timestampWith #-}
1319timestampWith :: (IsStream t, MonadAsync m, Functor (t m))
1320 => Double -> t m a -> t m (AbsTime, a)
1321timestampWith g stream = Z.zipWith (flip (,)) stream (absTimesWith g)
1323-- TBD: check performance vs a custom implementation without using zipWith.
1325-- /Internal/
1327{-# INLINE timestamped #-}
1328timestamped :: (IsStream t, MonadAsync m, Functor (t m))
1329 => t m a -> t m (AbsTime, a)
1330timestamped = timestampWith 0.01
1332-- | Pair each element in a stream with relative times starting from 0, using a
1333-- clock with the specified granularity. The time is measured just before the
1334-- element is consumed.
1336-- @
1337-- >>> S.mapM_ print $ S.timeIndexWith 0.01 $ S.delay 1 $ S.enumerateFromTo 1 3
1338-- @
1340-- /Internal/
1342{-# INLINE timeIndexWith #-}
1343timeIndexWith :: (IsStream t, MonadAsync m, Functor (t m))
1344 => Double -> t m a -> t m (RelTime64, a)
1345timeIndexWith g stream = Z.zipWith (flip (,)) stream (relTimesWith g)
1347-- | Pair each element in a stream with relative times starting from 0, using a
1348-- 10 ms granularity clock. The time is measured just before the element is
1349-- consumed.
1351-- @
1352-- >>> S.mapM_ print $ S.timeIndexed $ S.delay 1 $ S.enumerateFromTo 1 3
1353-- (RelTime64 (NanoSecond64 0),1)
1354-- (RelTime64 (NanoSecond64 996239000),2)
1355-- (RelTime64 (NanoSecond64 1996712000),3)
1356-- @
1358-- /Internal/
1360{-# INLINE timeIndexed #-}
1361timeIndexed :: (IsStream t, MonadAsync m, Functor (t m))
1362 => t m a -> t m (RelTime64, a)
1363timeIndexed = timeIndexWith 0.01
1365------------------------------------------------------------------------------
1366-- Searching
1367------------------------------------------------------------------------------
1369-- | Find all the indices where the value of the element in the stream is equal
1370-- to the given value.
1372-- > elemIndices a = findIndices (== a)
1374-- @since 0.5.0
1375{-# INLINE elemIndices #-}
1376elemIndices :: (IsStream t, Eq a, Monad m) => a -> t m a -> t m Int
1377elemIndices a = findIndices (== a)
1379------------------------------------------------------------------------------
1380-- Rolling map
1381------------------------------------------------------------------------------
1383-- XXX this is not a one-to-one map so calling it map may not be right.
1384-- We can perhaps call it zipWithTail or rollWith.
1386-- | Apply a function on every two successive elements of a stream. If the
1387-- stream consists of a single element the output is an empty stream.
1389-- This is the stream equivalent of the list idiom @zipWith f xs (tail xs)@.
1391-- /Internal/
1393{-# INLINE rollingMap #-}
1394rollingMap :: (IsStream t, Monad m) => (a -> a -> b) -> t m a -> t m b
1395rollingMap f m = fromStreamD $ D.rollingMap f $ toStreamD m
1397-- | Like 'rollingMap' but with an effectful map function.
1399-- /Internal/
1401{-# INLINE rollingMapM #-}
1402rollingMapM :: (IsStream t, Monad m) => (a -> a -> m b) -> t m a -> t m b
1403rollingMapM f m = fromStreamD $ D.rollingMapM f $ toStreamD m
1405------------------------------------------------------------------------------
1406-- Maybe Streams
1407------------------------------------------------------------------------------
1409-- | Map a 'Maybe' returning function to a stream, filter out the 'Nothing'
1410-- elements, and return a stream of values extracted from 'Just'.
1412-- Equivalent to:
1414-- @
1415-- mapMaybe f = S.map 'fromJust' . S.filter 'isJust' . S.map f
1416-- @
1418-- @since 0.3.0
1419{-# INLINE mapMaybe #-}
1420mapMaybe :: (IsStream t, Monad m) => (a -> Maybe b) -> t m a -> t m b
1421mapMaybe f m = fromStreamS $ S.mapMaybe f $ toStreamS m
1423-- | Like 'mapMaybe' but maps a monadic function.
1425-- Equivalent to:
1427-- @
1428-- mapMaybeM f = S.map 'fromJust' . S.filter 'isJust' . S.mapM f
1429-- @
1431-- /Concurrent (do not use with 'parallely' on infinite streams)/
1433-- @since 0.3.0
1434{-# INLINE_EARLY mapMaybeM #-}
1435mapMaybeM :: (IsStream t, MonadAsync m, Functor (t m))
1436 => (a -> m (Maybe b)) -> t m a -> t m b
1437mapMaybeM f = fmap fromJust . filter isJust . K.mapM f
1439{-# RULES "mapMaybeM serial" mapMaybeM = mapMaybeMSerial #-}
1440{-# INLINE mapMaybeMSerial #-}
1441mapMaybeMSerial :: Monad m => (a -> m (Maybe b)) -> SerialT m a -> SerialT m b
1442mapMaybeMSerial f m = fromStreamD $ D.mapMaybeM f $ toStreamD m
1444-- | In a stream of 'Maybe's, discard 'Nothing's and unwrap 'Just's.
1446-- /Internal/
1448catMaybes :: (IsStream t, Monad m, Functor (t m)) => t m (Maybe a) -> t m a
1449catMaybes = fmap fromJust . filter isJust
1451------------------------------------------------------------------------------
1452-- Either streams
1453------------------------------------------------------------------------------
1455-- | Discard 'Right's and unwrap 'Left's in an 'Either' stream.
1457-- /Internal/
1459lefts :: (IsStream t, Monad m, Functor (t m)) => t m (Either a b) -> t m a
1460lefts = fmap (fromLeft undefined) . filter isLeft
1462-- | Discard 'Left's and unwrap 'Right's in an 'Either' stream.
1464-- /Internal/
1466rights :: (IsStream t, Monad m, Functor (t m)) => t m (Either a b) -> t m b
1467rights = fmap (fromRight undefined) . filter isRight
1469------------------------------------------------------------------------------
1470-- Concurrent Application
1471------------------------------------------------------------------------------
1473-- | Parallel transform application operator; applies a stream transformation
1474-- function @t m a -> t m b@ to a stream @t m a@ concurrently; the input stream
1475-- is evaluated asynchronously in an independent thread yielding elements to a
1476-- buffer and the transformation function runs in another thread consuming the
1477-- input from the buffer. '|$' is just like regular function application
1478-- operator '$' except that it is concurrent.
1480-- If you read the signature as @(t m a -> t m b) -> (t m a -> t m b)@ you can
1481-- look at it as a transformation that converts a transform function to a
1482-- buffered concurrent transform function.
1484-- The following code prints a value every second even though each stage adds a
1485-- 1 second delay.
1488-- @
1489-- drain $
1490-- S.mapM (\\x -> threadDelay 1000000 >> print x)
1491-- |$ S.repeatM (threadDelay 1000000 >> return 1)
1492-- @
1494-- /Concurrent/
1496-- /Since: 0.3.0 ("Streamly")/
1498-- @since 0.8.0
1499{-# INLINE (|$) #-}
1500(|$) :: (IsStream t, MonadAsync m) => (t m a -> t m b) -> (t m a -> t m b)
1501-- (|$) f = f . Async.mkAsync
1502(|$) f = f . Par.mkParallel
1504infixr 0 |$
1506-- | Same as '|$'.
1508-- /Internal/
1510{-# INLINE applyAsync #-}
1511applyAsync :: (IsStream t, MonadAsync m)
1512 => (t m a -> t m b) -> (t m a -> t m b)
1513applyAsync = (|$)
1515-- | Parallel reverse function application operator for streams; just like the
1516-- regular reverse function application operator '&' except that it is
1517-- concurrent.
1519-- @
1520-- drain $
1521-- S.repeatM (threadDelay 1000000 >> return 1)
1522-- |& S.mapM (\\x -> threadDelay 1000000 >> print x)
1523-- @
1525-- /Concurrent/
1527-- /Since: 0.3.0 ("Streamly")/
1529-- @since 0.8.0
1530{-# INLINE (|&) #-}
1531(|&) :: (IsStream t, MonadAsync m) => t m a -> (t m a -> t m b) -> t m b
1532x |& f = f |$ x
1534infixl 1 |&