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
9module Streamly.Internal.Data.Stream.IsStream.Transform
12 -- | Pass through a 'Pipe'.
20 -- | Stateless one-to-one maps.
26 -- * Mapping Side Effects
35 -- * Scanning By 'Fold'
40 -- | Left scans. Stateful, mostly one-to-one maps.
51 -- XXX Once we have pipes the contravariant transformations can be
52 -- represented by attaching pipes before a transformation.
65 -- | Produce a subset of the stream.
71 -- , uniqBy -- by predicate e.g. to remove duplicate "/" in a path
72 -- , uniqOn -- to remove duplicate sequences
73 -- , pruneBy -- dropAround + uniqBy - like words
76 -- | Produce a subset of the stream trimmed at ends.
94 -- * Inserting Elements
95 -- | Produce a superset of the stream.
99 , intersperseM -- XXX naming
101 , intersperseSuffixBySpan
102 -- , intersperseBySpan
103 -- , intersperseByIndices -- using an index function/stream
105 -- * Inserting Side Effects
106 , intersperseM_ -- XXX naming
111 -- , intersperseByTime
112 -- , intersperseByEvent
123 -- * Position Indexing
130 -- , timestampedR -- timer
135 , findIndices -- XXX indicesBy
136 , elemIndices -- XXX indicesOf
139 -- | Map using the previous element.
144 -- Move these to Streamly.Data.Maybe.Stream?
145 , catMaybes -- XXX justs (like lefts/rights)
150 -- Move these to Streamly.Data.Either.Stream?
155 -- ** Concurrent Pipelines
156 -- | Run streaming stages concurrently.
163 -- ** Concurrency Control
185import Control.Concurrent (threadDelay)
186import Control.Monad (void)
187import Control.Monad.Catch (MonadCatch)
188import Control.Monad.IO.Class (MonadIO(..))
189import Control.Monad.Trans.Class (MonadTrans(..))
190import Data.Either (isLeft, isRight)
191import Data.Maybe (isJust, fromJust)
192import Streamly.Internal.BaseCompat (fromLeft, fromRight)
193import Streamly.Internal.Data.Fold.Types (Fold (..))
194import Streamly.Internal.Data.Pipe.Types (Pipe (..))
195import Streamly.Internal.Data.Stream.IsStream.Combinators
196 ( inspectMode, maxBuffer, maxThreads, rate, avgRate, minRate
197 , maxRate, constRate)
198import Streamly.Internal.Data.Stream.IsStream.Common
213import Streamly.Internal.Data.Stream.Prelude (fromStreamS, toStreamS)
214import Streamly.Internal.Data.Stream.Serial (SerialT)
215import Streamly.Internal.Data.Stream.StreamD (fromStreamD, toStreamD)
216import Streamly.Internal.Data.Stream.StreamK (IsStream)
217import Streamly.Internal.Data.SVar (MonadAsync, Rate(..))
218import Streamly.Internal.Data.Time.Units ( TimeUnit64, AbsTime, RelTime64)
220import qualified Streamly.Internal.Data.Fold as FL
221import qualified Streamly.Internal.Data.Stream.Parallel as Par
222import qualified Streamly.Internal.Data.Stream.Prelude as P
223import qualified Streamly.Internal.Data.Stream.Serial as Serial
224import qualified Streamly.Internal.Data.Stream.StreamD as D
225import qualified Streamly.Internal.Data.Stream.StreamK as K
226import qualified Streamly.Internal.Data.Stream.Zip as Z
227#ifdef USE_STREAMK_ONLY
228import qualified Streamly.Internal.Data.Stream.StreamK as S
230import qualified Streamly.Internal.Data.Stream.StreamD as S
234 ( filter, drop, dropWhile, take, takeWhile, foldr, map, mapM, sequence
235 , reverse, foldr1 , scanl, scanl1)
237------------------------------------------------------------------------------
239------------------------------------------------------------------------------
241-- | Use a 'Pipe' to transform a stream.
245{-# INLINE transform #-}
246transform :: (IsStream t, Monad m) => Pipe m a b -> t m a -> t m b
247transform pipe xs = fromStreamD $ D.transform pipe (toStreamD xs)
249------------------------------------------------------------------------------
250-- Transformation Folds
251------------------------------------------------------------------------------
253-- | Right fold to a streaming monad.
255-- > foldrS S.cons S.nil === id
257-- 'foldrS' can be used to perform stateless stream to stream transformations
258-- like map and filter in general. It can be coupled with a scan to perform
259-- stateful transformations. However, note that the custom map and filter
260-- routines can be much more efficient than this due to better stream fusion.
262-- >>> S.toList $ S.foldrS S.cons S.nil $ S.fromList [1..5]
265-- Find if any element in the stream is 'True':
267-- >>> 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)
270-- Map (+2) on odd elements and filter out the even elements:
272-- >>> 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)
275-- 'foldrM' can also be represented in terms of 'foldrS', however, the former
276-- is much more efficient:
278-- > foldrM f z s = runIdentityT $ foldrS (\x xs -> lift $ f x (runIdentityT xs)) (lift z) s
282foldrS :: IsStream t => (a -> t m b -> t m b) -> t m b -> t m a -> t m b
285-- | Right fold to a transformer monad. This is the most general right fold
286-- function. 'foldrS' is a special case of 'foldrT', however 'foldrS'
287-- implementation can be more efficient:
290-- > foldrM f z s = runIdentityT $ foldrT (\x xs -> lift $ f x (runIdentityT xs)) (lift z) s
292-- 'foldrT' can be used to translate streamly streams to other transformer
293-- monads e.g. to a different streaming type.
297foldrT :: (IsStream t, Monad m, Monad (s m), MonadTrans s)
298 => (a -> s m b -> s m b) -> s m b -> t m a -> s m b
299foldrT f z s = S.foldrT f z (toStreamS s)
301------------------------------------------------------------------------------
302-- Transformation by Mapping
303------------------------------------------------------------------------------
307-- mapM f = sequence . map f
310-- Apply a monadic function to each element of the stream and replace it with
311-- the output of the resulting action.
314-- > drain $ S.mapM putStr $ S.fromList ["a", "b", "c"]
317-- drain $ S.replicateM 10 (return 1)
318-- & (serially . S.mapM (\\x -> threadDelay 1000000 >> print x))
320-- drain $ S.replicateM 10 (return 1)
321-- & (asyncly . S.mapM (\\x -> threadDelay 1000000 >> print x))
324-- /Concurrent (do not use with 'parallely' on infinite streams)/
327{-# INLINE_EARLY mapM #-}
328mapM :: (IsStream t, MonadAsync m) => (a -> m b) -> t m a -> t m b
331{-# RULES "mapM serial" mapM = mapMSerial #-}
332{-# INLINE mapMSerial #-}
333mapMSerial :: Monad m => (a -> m b) -> SerialT m a -> SerialT m b
334mapMSerial = Serial.mapM
341-- Replace the elements of a stream of monadic actions with the outputs of
345-- > drain $ S.sequence $ S.fromList [putStr "a", putStr "b", putStrLn "c"]
348-- drain $ S.replicateM 10 (return $ threadDelay 1000000 >> print 1)
349-- & (serially . S.sequence)
351-- drain $ S.replicateM 10 (return $ threadDelay 1000000 >> print 1)
352-- & (asyncly . S.sequence)
355-- /Concurrent (do not use with 'parallely' on infinite streams)/
358{-# INLINE sequence #-}
359sequence :: (IsStream t, MonadAsync m) => t m (m a) -> t m a
360sequence m = fromStreamS $ S.sequence (toStreamS m)
362------------------------------------------------------------------------------
363-- Mapping side effects
364------------------------------------------------------------------------------
366-- | Tap the data flowing through a stream into a 'Fold'. For example, you may
367-- add a tap to log the contents flowing through the stream. The fold is used
368-- only for effects, its result is discarded.
373-- -----stream m a ---------------stream m a-----
378-- > S.drain $ S.tap (FL.drainBy print) (S.enumerateFromTo 1 2)
383-- Compare with 'trace'.
387tap :: (IsStream t, Monad m) => FL.Fold m a b -> t m a -> t m a
388tap f xs = D.fromStreamD $ D.tap f (D.toStreamD xs)
390-- | @tapOffsetEvery offset n@ taps every @n@th element in the stream
391-- starting at @offset@. @offset@ can be between @0@ and @n - 1@. Offset 0
392-- means start at the first element in the stream. If the offset is outside
393-- this range then @offset `mod` n@ is used as offset.
396-- >>> S.drain $ S.tapOffsetEvery 0 2 (FL.rmapM print FL.toList) $ S.enumerateFromTo 0 10
402{-# INLINE tapOffsetEvery #-}
403tapOffsetEvery :: (IsStream t, Monad m)
404 => Int -> Int -> FL.Fold m a b -> t m a -> t m a
405tapOffsetEvery offset n f xs =
406 D.fromStreamD $ D.tapOffsetEvery offset n f (D.toStreamD xs)
408-- | Redirect a copy of the stream to a supplied fold and run it concurrently
409-- in an independent thread. The fold may buffer some elements. The buffer size
410-- is determined by the prevailing 'maxBuffer' setting.
415-- -----stream m a ---------------stream m a-----
420-- > S.drain $ S.tapAsync (S.mapM_ print) (S.enumerateFromTo 1 2)
425-- Exceptions from the concurrently running fold are propagated to the current
426-- computation. Note that, because of buffering in the fold, exceptions may be
427-- delayed and may not correspond to the current element being processed in the
428-- parent stream, but we guarantee that before the parent stream stops the tap
429-- finishes and all exceptions from it are drained.
432-- Compare with 'tap'.
435{-# INLINE tapAsync #-}
436tapAsync :: (IsStream t, MonadAsync m) => FL.Fold m a b -> t m a -> t m a
437tapAsync f xs = D.fromStreamD $ Par.tapAsyncF f (D.toStreamD xs)
439-- | @pollCounts predicate transform fold stream@ counts those elements in the
440-- stream that pass the @predicate@. The resulting count stream is sent to
441-- another thread which transforms it using @transform@ and then folds it using
442-- @fold@. The thread is automatically cleaned up if the stream stops or
443-- aborts due to exception.
445-- For example, to print the count of elements processed every second:
448-- > S.drain $ S.pollCounts (const True) (S.rollingMap (-) . S.delayPost 1) (FL.drainBy print)
449-- $ S.enumerateFrom 0
452-- Note: This may not work correctly on 32-bit machines.
456{-# INLINE pollCounts #-}
458 (IsStream t, MonadAsync m)
460 -> (t m Int -> t m Int)
464pollCounts predicate transf f xs =
466 $ D.pollCounts predicate (D.toStreamD . transf . D.fromStreamD) f
469-- | Calls the supplied function with the number of elements consumed
470-- every @n@ seconds. The given function is run in a separate thread
471-- until the end of the stream. In case there is an exception in the
472-- stream the thread is killed during the next major GC.
474-- Note: The action is not guaranteed to run if the main thread exits.
477-- > delay n = threadDelay (round $ n * 1000000) >> return n
478-- > S.drain $ S.tapRate 2 (\\n -> print $ show n ++ " elements processed") (delay 1 S.|: delay 0.5 S.|: delay 0.5 S.|: S.nil)
479-- 2 elements processed
480-- 1 elements processed
483-- Note: This may not work correctly on 32-bit machines.
486{-# INLINE tapRate #-}
488 (IsStream t, MonadAsync m, MonadCatch m)
493tapRate n f xs = D.fromStreamD $ D.tapRate n f $ D.toStreamD xs
495-- | Apply a monadic function to each element flowing through the stream and
496-- discard the results.
499-- > S.drain $ S.trace print (S.enumerateFromTo 1 2)
504-- Compare with 'tap'.
508trace :: (IsStream t, MonadAsync m) => (a -> m b) -> t m a -> t m a
509trace f = mapM (\x -> void (f x) >> return x)
511-- | Perform a side effect before yielding each element of the stream and
512-- discard the results.
515-- > S.drain $ S.trace_ (print "got here") (S.enumerateFromTo 1 2)
520-- See also: 'trace', 'interspersePrefix_'
524trace_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
525trace_ eff = Serial.mapM (\x -> eff >> return x)
527------------------------------------------------------------------------------
528-- Scanning with a Fold
529------------------------------------------------------------------------------
531-- | Scan a stream using the given monadic fold.
535scan :: (IsStream t, Monad m) => Fold m a b -> t m a -> t m b
538-- | Postscan a stream using the given monadic fold.
541{-# INLINE postscan #-}
542postscan :: (IsStream t, Monad m) => Fold m a b -> t m a -> t m b
543postscan = P.postscanOnce
545------------------------------------------------------------------------------
546-- Scanning - Transformation by Folding
547------------------------------------------------------------------------------
549-- XXX It may be useful to have a version of scan where we can keep the
550-- accumulator independent of the value emitted. So that we do not necessarily
551-- have to keep a value in the accumulator which we are not using. We can pass
552-- an extraction function that will take the accumulator and the current value
553-- of the element and emit the next value in the stream. That will also make it
554-- possible to modify the accumulator after using it. In fact, the step function
555-- can return new accumulator and the value to be emitted. The signature would
556-- be more like mapAccumL. Or we can change the signature of scanx to
559-- | Strict left scan with an extraction function. Like 'scanl'', but applies a
560-- user supplied extraction function (the third argument) at each step. This is
561-- designed to work with the @foldl@ library. The suffix @x@ is a mnemonic for
566-- /Since: 0.7.0 (Monad m constraint)/
567{-# DEPRECATED scanx "Please use scanl followed by map instead." #-}
569scanx :: (IsStream t, Monad m) => (x -> a -> x) -> x -> (x -> b) -> t m a -> t m b
572-- XXX this needs to be concurrent
573-- XXX because of the use of D.cons for appending, scanlM' has quadratic
574-- complexity when iterated over a stream. We should use StreamK style scanlM'
575-- for linear performance on iteration.
577-- | Like 'scanl'' but with a monadic step function and a monadic seed.
581-- /Since: 0.8.0 (signature change)/
582{-# INLINE scanlM' #-}
583scanlM' :: (IsStream t, Monad m) => (b -> a -> m b) -> m b -> t m a -> t m b
584scanlM' step begin m = fromStreamD $ D.scanlM' step begin $ toStreamD m
586-- XXX because of the use of D.cons for appending, scanl' has quadratic
587-- complexity when iterated over a stream. We should use StreamK style scanlM'
588-- for linear performance on iteration.
590-- | Strict left scan. Like 'map', 'scanl'' too is a one to one transformation,
591-- however it adds an extra element.
594-- > S.toList $ S.scanl' (+) 0 $ fromList [1,2,3,4]
599-- > S.toList $ S.scanl' (flip (:)) [] $ S.fromList [1,2,3,4]
600-- [[],[1],[2,1],[3,2,1],[4,3,2,1]]
603-- The output of 'scanl'' is the initial value of the accumulator followed by
604-- all the intermediate steps and the final result of 'foldl''.
606-- By streaming the accumulated state after each fold step, we can share the
607-- state across multiple stages of stream composition. Each stage can modify or
608-- extend the state, do some processing with it and emit it for the next stage,
609-- thus modularizing the stream processing. This can be useful in
610-- stateful or event-driven programming.
612-- Consider the following monolithic example, computing the sum and the product
613-- of the elements in a stream in one go using a @foldl'@:
616-- > S.foldl' (\\(s, p) x -> (s + x, p * x)) (0,1) $ S.fromList \[1,2,3,4]
620-- Using @scanl'@ we can make it modular by computing the sum in the first
621-- stage and passing it down to the next stage for computing the product:
624-- > S.foldl' (\\(_, p) (s, x) -> (s, p * x)) (0,1)
625-- $ S.scanl' (\\(s, _) x -> (s + x, x)) (0,1)
626-- $ S.fromList \[1,2,3,4]
630-- IMPORTANT: 'scanl'' evaluates the accumulator to WHNF. To avoid building
631-- lazy expressions inside the accumulator, it is recommended that a strict
632-- data structure is used for accumulator.
634-- See also: 'usingStateT'
638scanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
639scanl' step z m = fromStreamS $ S.scanl' step z $ toStreamS m
641-- | Like 'scanl'' but does not stream the initial value of the accumulator.
643-- > postscanl' f z xs = S.drop 1 $ S.scanl' f z xs
646{-# INLINE postscanl' #-}
647postscanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
648postscanl' step z m = fromStreamD $ D.postscanl' step z $ toStreamD m
650-- XXX prescanl does not sound very useful, enable only if there is a
651-- compelling use case.
653-- | Like scanl' but does not stream the final value of the accumulator.
656{-# INLINE prescanl' #-}
657prescanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
658prescanl' step z m = fromStreamD $ D.prescanl' step z $ toStreamD m
660-- XXX this needs to be concurrent
661-- | Like prescanl' but with a monadic step function and a monadic seed.
664{-# INLINE prescanlM' #-}
665prescanlM' :: (IsStream t, Monad m) => (b -> a -> m b) -> m b -> t m a -> t m b
666prescanlM' step z m = fromStreamD $ D.prescanlM' step z $ toStreamD m
668-- XXX this needs to be concurrent
669-- | Like 'scanl1'' but with a monadic step function.
672{-# INLINE scanl1M' #-}
673scanl1M' :: (IsStream t, Monad m) => (a -> a -> m a) -> t m a -> t m a
674scanl1M' step m = fromStreamD $ D.scanl1M' step $ toStreamD m
676-- | Like 'scanl'' but for a non-empty stream. The first element of the stream
677-- is used as the initial value of the accumulator. Does nothing if the stream
681-- > S.toList $ S.scanl1 (+) $ fromList [1,2,3,4]
686{-# INLINE scanl1' #-}
687scanl1' :: (IsStream t, Monad m) => (a -> a -> a) -> t m a -> t m a
688scanl1' step m = fromStreamD $ D.scanl1' step $ toStreamD m
690------------------------------------------------------------------------------
692------------------------------------------------------------------------------
694-- | Include only those elements that pass a predicate.
698#if __GLASGOW_HASKELL__ != 802
699-- GHC 8.2.2 crashes with this code, when used with "stack"
700filter :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m a
701filter p m = fromStreamS $ S.filter p $ toStreamS m
703filter :: IsStream t => (a -> Bool) -> t m a -> t m a
707-- | Same as 'filter' but with a monadic predicate.
710{-# INLINE filterM #-}
711filterM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
712filterM p m = fromStreamD $ D.filterM p $ toStreamD m
714-- | Drop repeated elements that are adjacent to each other.
718uniq :: (Eq a, IsStream t, Monad m) => t m a -> t m a
719uniq = fromStreamD . D.uniq . toStreamD
721-- | Deletes the first occurrence of the element in the stream that satisfies
722-- the given equality predicate.
725-- > S.toList $ S.deleteBy (==) 3 $ S.fromList [1,3,3,5]
730{-# INLINE deleteBy #-}
731deleteBy :: (IsStream t, Monad m) => (a -> a -> Bool) -> a -> t m a -> t m a
732deleteBy cmp x m = fromStreamS $ S.deleteBy cmp x (toStreamS m)
734------------------------------------------------------------------------------
736------------------------------------------------------------------------------
738-- | Same as 'takeWhile' but with a monadic predicate.
741{-# INLINE takeWhileM #-}
742takeWhileM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
743takeWhileM p m = fromStreamD $ D.takeWhileM p $ toStreamD m
745-- | @takeByTime duration@ yields stream elements upto specified time
746-- @duration@. The duration starts when the stream is evaluated for the first
747-- time, before the first element is yielded. The time duration is checked
748-- before generating each element, if the duration has expired the stream
751-- The total time taken in executing the stream is guaranteed to be /at least/
752-- @duration@, however, because the duration is checked before generating an
753-- element, the upper bound is indeterminate and depends on the time taken in
754-- generating and processing the last element.
756-- No element is yielded if the duration is zero. At least one element is
757-- yielded if the duration is non-zero.
761{-# INLINE takeByTime #-}
762takeByTime ::(MonadIO m, IsStream t, TimeUnit64 d) => d -> t m a -> t m a
763takeByTime d = fromStreamD . D.takeByTime d . toStreamD
765-- | Drop elements in the stream as long as the predicate succeeds and then
766-- take the rest of the stream.
769{-# INLINE dropWhile #-}
770dropWhile :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m a
771dropWhile p m = fromStreamS $ S.dropWhile p $ toStreamS m
773-- | Same as 'dropWhile' but with a monadic predicate.
776{-# INLINE dropWhileM #-}
777dropWhileM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
778dropWhileM p m = fromStreamD $ D.dropWhileM p $ toStreamD m
780-- | @dropByTime duration@ drops stream elements until specified @duration@ has
781-- passed. The duration begins when the stream is evaluated for the first
782-- time. The time duration is checked /after/ generating a stream element, the
783-- element is yielded if the duration has expired otherwise it is dropped.
785-- The time elapsed before starting to generate the first element is /at most/
786-- @duration@, however, because the duration expiry is checked after the
787-- element is generated, the lower bound is indeterminate and depends on the
788-- time taken in generating an element.
790-- All elements are yielded if the duration is zero.
794{-# INLINE dropByTime #-}
795dropByTime ::(MonadIO m, IsStream t, TimeUnit64 d) => d -> t m a -> t m a
796dropByTime d = fromStreamD . D.dropByTime d . toStreamD
798------------------------------------------------------------------------------
800------------------------------------------------------------------------------
802-- | @insertBy cmp elem stream@ inserts @elem@ before the first element in
803-- @stream@ that is less than @elem@ when compared using @cmp@.
806-- insertBy cmp x = 'mergeBy' cmp ('yield' x)
810-- > S.toList $ S.insertBy compare 2 $ S.fromList [1,3,5]
815{-# INLINE insertBy #-}
817 (IsStream t, Monad m) => (a -> a -> Ordering) -> a -> t m a -> t m a
818insertBy cmp x m = fromStreamS $ S.insertBy cmp x (toStreamS m)
820-- | Insert a pure value between successive elements of a stream.
823-- > S.toList $ S.intersperse ',' $ S.fromList "hello"
828{-# INLINE intersperse #-}
829intersperse :: (IsStream t, MonadAsync m) => a -> t m a -> t m a
830intersperse a = fromStreamS . S.intersperse a . toStreamS
832-- | Insert a side effect before consuming an element of a stream except the
836-- >>> S.drain $ S.trace putChar $ S.intersperseM_ (putChar '.') $ S.fromList "hello"
841{-# INLINE intersperseM_ #-}
842intersperseM_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
843intersperseM_ m = fromStreamD . D.intersperseM_ m . toStreamD
846-- | Intersperse a monadic action into the input stream after every @n@
850-- > S.toList $ S.intersperseBySpan 2 (return ',') $ S.fromList "hello"
855{-# INLINE intersperseBySpan #-}
856intersperseBySpan :: IsStream t => Int -> m a -> t m a -> t m a
857intersperseBySpan _n _f _xs = undefined
860-- | Insert an effect and its output after consuming an element of a stream.
863-- >>> S.toList $ S.trace putChar $ S.intersperseSuffix (putChar '.' >> return ',') $ S.fromList "hello"
864-- > h.,e.,l.,l.,o.,"h,e,l,l,o,"
868{-# INLINE intersperseSuffix #-}
869intersperseSuffix :: (IsStream t, MonadAsync m) => m a -> t m a -> t m a
870intersperseSuffix m = fromStreamD . D.intersperseSuffix m . toStreamD
872-- | Insert a side effect after consuming an element of a stream.
875-- > S.mapM_ putChar $ S.intersperseSuffix_ (threadDelay 1000000) $ S.fromList "hello"
880{-# INLINE intersperseSuffix_ #-}
881intersperseSuffix_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
882intersperseSuffix_ m = fromStreamD . D.intersperseSuffix_ m . toStreamD
884-- | Like 'intersperseSuffix' but intersperses an effectful action into the
885-- input stream after every @n@ elements and after the last element.
888-- > S.toList $ S.intersperseSuffixBySpan 2 (return ',') $ S.fromList "hello"
894{-# INLINE intersperseSuffixBySpan #-}
895intersperseSuffixBySpan :: (IsStream t, MonadAsync m)
896 => Int -> m a -> t m a -> t m a
897intersperseSuffixBySpan n eff =
898 fromStreamD . D.intersperseSuffixBySpan n eff . toStreamD
900-- | Insert a side effect before consuming an element of a stream.
903-- >>> S.toList $ S.trace putChar $ S.interspersePrefix_ (putChar '.' >> return ',') $ S.fromList "hello"
904-- > .h.e.l.l.o"hello"
913{-# INLINE interspersePrefix_ #-}
914interspersePrefix_ :: (IsStream t, MonadAsync m) => m b -> t m a -> t m a
915interspersePrefix_ m = mapM (\x -> void m >> return x)
917------------------------------------------------------------------------------
919------------------------------------------------------------------------------
921-- Note: delay must be serial.
923-- | Introduce a delay of specified seconds before consuming an element of the
924-- stream except the first one.
927-- >>> S.mapM_ print $ S.timestamped $ S.delay 1 $ S.enumerateFromTo 1 3
928-- > (AbsTime (TimeSpec {sec = 2502706, nsec = 751137000}),1)
929-- > (AbsTime (TimeSpec {sec = 2502707, nsec = 743535000}),2)
930-- > (AbsTime (TimeSpec {sec = 2502708, nsec = 749758000}),3)
936delay :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
937delay n = intersperseM_ $ liftIO $ threadDelay $ round $ n * 1000000
939-- Note: delay must be serial.
941-- | Introduce a delay of specified seconds after consuming an element of a
945-- >>> S.mapM_ print $ S.timestamped $ S.delayPost 1 $ S.enumerateFromTo 1 3
946-- > (AbsTime (TimeSpec {sec = 2502826, nsec = 119030000}),1)
947-- > (AbsTime (TimeSpec {sec = 2502827, nsec = 111393000}),2)
948-- > (AbsTime (TimeSpec {sec = 2502828, nsec = 112221000}),3)
953{-# INLINE delayPost #-}
954delayPost :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
955delayPost n = intersperseSuffix_ $ liftIO $ threadDelay $ round $ n * 1000000
957-- Note: delay must be serial, that's why 'trace_' is used.
959-- | Introduce a delay of specified seconds before consuming an element of a
963-- >>> S.mapM_ print $ S.timestamped $ S.delayPre 1 $ S.enumerateFromTo 1 3
964-- > (AbsTime (TimeSpec {sec = 2502207, nsec = 533177000}),1)
965-- > (AbsTime (TimeSpec {sec = 2502208, nsec = 530859000}),2)
966-- > (AbsTime (TimeSpec {sec = 2502209, nsec = 531619000}),3)
971{-# INLINE delayPre #-}
972delayPre :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
973delayPre n = trace_ $ liftIO $ threadDelay $ round $ n * 1000000
975------------------------------------------------------------------------------
976-- Reorder in sequence
977------------------------------------------------------------------------------
979-- | Buffer until the next element in sequence arrives. The function argument
980-- determines the difference in sequence numbers. This could be useful in
981-- implementing sequenced streams, for example, TCP reassembly.
985{-# INLINE reassembleBy #-}
987 :: -- (IsStream t, Monad m) =>
992reassembleBy = undefined
994------------------------------------------------------------------------------
996------------------------------------------------------------------------------
999-- > indexed = S.postscanl' (\(i, _) x -> (i + 1, x)) (-1,undefined)
1000-- > indexed = S.zipWith (,) (S.enumerateFrom 0)
1002-- Pair each element in a stream with its index, starting from index 0.
1005-- > S.toList $ S.indexed $ S.fromList "hello"
1006-- [(0,'h'),(1,'e'),(2,'l'),(3,'l'),(4,'o')]
1010{-# INLINE indexed #-}
1011indexed :: (IsStream t, Monad m) => t m a -> t m (Int, a)
1012indexed = fromStreamD . D.indexed . toStreamD
1015-- > indexedR n = S.postscanl' (\(i, _) x -> (i - 1, x)) (n + 1,undefined)
1016-- > indexedR n = S.zipWith (,) (S.enumerateFromThen n (n - 1))
1018-- Pair each element in a stream with its index, starting from the
1019-- given index @n@ and counting down.
1022-- > S.toList $ S.indexedR 10 $ S.fromList "hello"
1023-- [(10,'h'),(9,'e'),(8,'l'),(7,'l'),(6,'o')]
1027{-# INLINE indexedR #-}
1028indexedR :: (IsStream t, Monad m) => Int -> t m a -> t m (Int, a)
1029indexedR n = fromStreamD . D.indexedR n . toStreamD
1031-------------------------------------------------------------------------------
1033-------------------------------------------------------------------------------
1035-- Note: The timestamp stream must be the second stream in the zip so that the
1036-- timestamp is generated after generating the stream element and not before.
1037-- If we do not do that then the following example will generate the same
1038-- timestamp for first two elements:
1040-- S.mapM_ print $ S.timestamped $ S.delay $ S.enumerateFromTo 1 3
1042-- | Pair each element in a stream with an absolute timestamp, using a clock of
1043-- specified granularity. The timestamp is generated just before the element
1047-- >>> S.mapM_ print $ S.timestampWith 0.01 $ S.delay 1 $ S.enumerateFromTo 1 3
1052{-# INLINE timestampWith #-}
1053timestampWith :: (IsStream t, MonadAsync m, Functor (t m))
1054 => Double -> t m a -> t m (AbsTime, a)
1055timestampWith g stream = Z.zipWith (flip (,)) stream (absTimesWith g)
1057-- TBD: check performance vs a custom implementation without using zipWith.
1061{-# INLINE timestamped #-}
1062timestamped :: (IsStream t, MonadAsync m, Functor (t m))
1063 => t m a -> t m (AbsTime, a)
1064timestamped = timestampWith 0.01
1066-- | Pair each element in a stream with relative times starting from 0, using a
1067-- clock with the specified granularity. The time is measured just before the
1068-- element is consumed.
1071-- >>> S.mapM_ print $ S.timeIndexWith 0.01 $ S.delay 1 $ S.enumerateFromTo 1 3
1076{-# INLINE timeIndexWith #-}
1077timeIndexWith :: (IsStream t, MonadAsync m, Functor (t m))
1078 => Double -> t m a -> t m (RelTime64, a)
1079timeIndexWith g stream = Z.zipWith (flip (,)) stream (relTimesWith g)
1081-- | Pair each element in a stream with relative times starting from 0, using a
1082-- 10 ms granularity clock. The time is measured just before the element is
1086-- >>> S.mapM_ print $ S.timeIndexed $ S.delay 1 $ S.enumerateFromTo 1 3
1087-- (RelTime64 (NanoSecond64 0),1)
1088-- (RelTime64 (NanoSecond64 996239000),2)
1089-- (RelTime64 (NanoSecond64 1996712000),3)
1094{-# INLINE timeIndexed #-}
1095timeIndexed :: (IsStream t, MonadAsync m, Functor (t m))
1096 => t m a -> t m (RelTime64, a)
1097timeIndexed = timeIndexWith 0.01
1099------------------------------------------------------------------------------
1101------------------------------------------------------------------------------
1103-- | Find all the indices where the value of the element in the stream is equal
1104-- to the given value.
1106-- > elemIndices a = findIndices (== a)
1109{-# INLINE elemIndices #-}
1110elemIndices :: (IsStream t, Eq a, Monad m) => a -> t m a -> t m Int
1111elemIndices a = findIndices (== a)
1113------------------------------------------------------------------------------
1115------------------------------------------------------------------------------
1117-- XXX this is not a one-to-one map so calling it map may not be right.
1118-- We can perhaps call it zipWithTail or rollWith.
1120-- | Apply a function on every two successive elements of a stream. If the
1121-- stream consists of a single element the output is an empty stream.
1123-- This is the stream equivalent of the list idiom @zipWith f xs (tail xs)@.
1127{-# INLINE rollingMap #-}
1128rollingMap :: (IsStream t, Monad m) => (a -> a -> b) -> t m a -> t m b
1129rollingMap f m = fromStreamD $ D.rollingMap f $ toStreamD m
1131-- | Like 'rollingMap' but with an effectful map function.
1135{-# INLINE rollingMapM #-}
1136rollingMapM :: (IsStream t, Monad m) => (a -> a -> m b) -> t m a -> t m b
1137rollingMapM f m = fromStreamD $ D.rollingMapM f $ toStreamD m
1139------------------------------------------------------------------------------
1141------------------------------------------------------------------------------
1143-- | Map a 'Maybe' returning function to a stream, filter out the 'Nothing'
1144-- elements, and return a stream of values extracted from 'Just'.
1149-- mapMaybe f = S.map 'fromJust' . S.filter 'isJust' . S.map f
1153{-# INLINE mapMaybe #-}
1154mapMaybe :: (IsStream t, Monad m) => (a -> Maybe b) -> t m a -> t m b
1155mapMaybe f m = fromStreamS $ S.mapMaybe f $ toStreamS m
1157-- | Like 'mapMaybe' but maps a monadic function.
1162-- mapMaybeM f = S.map 'fromJust' . S.filter 'isJust' . S.mapM f
1165-- /Concurrent (do not use with 'parallely' on infinite streams)/
1168{-# INLINE_EARLY mapMaybeM #-}
1169mapMaybeM :: (IsStream t, MonadAsync m, Functor (t m))
1170 => (a -> m (Maybe b)) -> t m a -> t m b
1171mapMaybeM f = fmap fromJust . filter isJust . K.mapM f
1173{-# RULES "mapMaybeM serial" mapMaybeM = mapMaybeMSerial #-}
1174{-# INLINE mapMaybeMSerial #-}
1175mapMaybeMSerial :: Monad m => (a -> m (Maybe b)) -> SerialT m a -> SerialT m b
1176mapMaybeMSerial f m = fromStreamD $ D.mapMaybeM f $ toStreamD m
1178-- | In a stream of 'Maybe's, discard 'Nothing's and unwrap 'Just's.
1182catMaybes :: (IsStream t, Monad m, Functor (t m)) => t m (Maybe a) -> t m a
1183catMaybes = fmap fromJust . filter isJust
1185------------------------------------------------------------------------------
1187------------------------------------------------------------------------------
1189-- | Discard 'Right's and unwrap 'Left's in an 'Either' stream.
1193lefts :: (IsStream t, Monad m, Functor (t m)) => t m (Either a b) -> t m a
1194lefts = fmap (fromLeft undefined) . filter isLeft
1196-- | Discard 'Left's and unwrap 'Right's in an 'Either' stream.
1200rights :: (IsStream t, Monad m, Functor (t m)) => t m (Either a b) -> t m b
1201rights = fmap (fromRight undefined) . filter isRight
1203------------------------------------------------------------------------------
1204-- Concurrent Application
1205------------------------------------------------------------------------------
1207-- | Parallel transform application operator; applies a stream transformation
1208-- function @t m a -> t m b@ to a stream @t m a@ concurrently; the input stream
1209-- is evaluated asynchronously in an independent thread yielding elements to a
1210-- buffer and the transformation function runs in another thread consuming the
1211-- input from the buffer. '|$' is just like regular function application
1212-- operator '$' except that it is concurrent.
1214-- If you read the signature as @(t m a -> t m b) -> (t m a -> t m b)@ you can
1215-- look at it as a transformation that converts a transform function to a
1216-- buffered concurrent transform function.
1218-- The following code prints a value every second even though each stage adds a
1224-- S.mapM (\\x -> threadDelay 1000000 >> print x)
1225-- |$ S.repeatM (threadDelay 1000000 >> return 1)
1230-- /Since: 0.3.0 ("Streamly")/
1234(|$) :: (IsStream t, MonadAsync m) => (t m a -> t m b) -> (t m a -> t m b)
1235-- (|$) f = f . Async.mkAsync
1236(|$) f = f . Par.mkParallel
1244{-# INLINE applyAsync #-}
1245applyAsync :: (IsStream t, MonadAsync m)
1246 => (t m a -> t m b) -> (t m a -> t m b)
1249-- | Parallel reverse function application operator for streams; just like the
1250-- regular reverse function application operator '&' except that it is
1255-- S.repeatM (threadDelay 1000000 >> return 1)
1256-- |& S.mapM (\\x -> threadDelay 1000000 >> print x)
1261-- /Since: 0.3.0 ("Streamly")/
1265(|&) :: (IsStream t, MonadAsync m) => t m a -> (t m a -> t m b) -> t m b
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list