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'.
21 -- | Stateless one-to-one maps.
27 -- * Mapping Side Effects (Observation)
28 -- | See also the intersperse*_ combinators.
38 -- * Scanning By 'Fold'
44 -- | Left scans. Stateful, mostly one-to-one maps.
56 -- XXX Once we have pipes the contravariant transformations can be
57 -- represented by attaching pipes before a transformation.
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.
86 -- | Produce a subset of the stream trimmed at ends.
105 -- * Inserting Elements
106 -- | Produce a superset of the stream. This is the opposite of
107 -- filtering/sampling. We can always use concatMap and scan for inserting
108 -- but these combinators are more efficient and convenient.
110 -- Element agnostic (Opposite of sampling)
112 , intersperseM -- XXX naming
116 , intersperseSuffixBySpan
119 -- , interspersePrefix
120 -- , interspersePrefixBySpan
122 -- * Inserting Side Effects/Time
123 , intersperseM_ -- XXX naming
130 -- * Element Aware Insertion
131 -- | Opposite of filtering
133 -- , intersperseByBefore
134 -- , intersperseByAfter
141 -- * Position Indexing
148 -- , timestampedR -- timer
153 , findIndices -- XXX indicesBy
154 , elemIndices -- XXX indicesOf
157 -- | Map using the previous element.
163 -- Move these to Streamly.Data.Maybe.Stream?
164 , catMaybes -- XXX justs (like lefts/rights)
169 -- Move these to Streamly.Data.Either.Stream?
174 -- * Concurrent Evaluation
175 -- ** Concurrent Pipelines
176 -- | Run streaming stages concurrently.
184 -- ** Concurrency Control
187 -- ** Buffering and Sampling
188 -- | Evaluate strictly using a buffer of results. When the buffer becomes
189 -- full we can block, drop the new elements, drop the oldest element and
190 -- insert the new at the end or keep dropping elements uniformly to match
191 -- the rate of the consumer.
198 -- | Evaluate the stream at uniform intervals to maintain a specified
217import Control.Concurrent (threadDelay)
218import Control.Monad (void)
219import Control.Monad.IO.Class (MonadIO(..))
220import Control.Monad.Trans.Class (MonadTrans(..))
221import Data.Either (isLeft, isRight, fromLeft, fromRight)
222import Data.Kind (Type)
223import Data.Maybe (isJust, fromJust)
224import Streamly.Internal.Data.Fold.Type (Fold (..))
225import Streamly.Internal.Data.Pipe.Type (Pipe (..))
226import Streamly.Internal.Data.Stream.IsStream.Combinators
227 ( inspectMode, maxBuffer, maxThreads, rate, avgRate, minRate
228 , maxRate, constRate)
229import Streamly.Internal.Data.Stream.IsStream.Common
249import Streamly.Internal.Control.Concurrent (MonadAsync)
250import Streamly.Internal.Data.Stream.IsStream.Type
251 (IsStream(..), fromStreamS, toStreamS, fromStreamD, toStreamD, toConsK)
252import Streamly.Internal.Data.Stream.Serial (SerialT)
253import Streamly.Internal.Data.SVar (Rate(..))
254import Streamly.Internal.Data.Time.Units (TimeUnit64, AbsTime, RelTime64)
256import qualified Streamly.Internal.Data.Fold as FL
257import qualified Streamly.Internal.Data.Stream.Parallel as Par
258import qualified Streamly.Internal.Data.Stream.Serial as Serial
259import qualified Streamly.Internal.Data.Stream.StreamD as D
260import qualified Streamly.Internal.Data.Stream.StreamK.Type as K
261#ifdef USE_STREAMK_ONLY
262import qualified Streamly.Internal.Data.Stream.StreamK as S
264import qualified Streamly.Internal.Data.Stream.StreamD as S
266import qualified Prelude
269 ( filter, drop, dropWhile, take, takeWhile, foldr, map, mapM, sequence
270 , reverse, foldr1 , scanl, scanl1, zipWith)
275-- >>> import Control.Concurrent (threadDelay)
276-- >>> import Data.Function ((&))
277-- >>> import Streamly.Prelude ((|$))
278-- >>> import Prelude hiding ( filter, drop, dropWhile, take, takeWhile, foldr, map, mapM, sequence, reverse, foldr1 , scanl, scanl1)
279-- >>> import qualified Streamly.Prelude as Stream
280-- >>> import Streamly.Internal.Data.Stream.IsStream as Stream
281-- >>> import qualified Streamly.Data.Fold as Fold
282-- >>> import qualified Streamly.Internal.Data.Fold as Fold
283-- >>> import System.IO (stdout, hSetBuffering, BufferMode(LineBuffering))
285-- >>> hSetBuffering stdout LineBuffering
287------------------------------------------------------------------------------
289------------------------------------------------------------------------------
291-- | Use a 'Pipe' to transform a stream.
295{-# INLINE transform #-}
296transform :: (IsStream t, Monad m) => Pipe m a b -> t m a -> t m b
297transform pipe xs = fromStreamD $ D.transform pipe (toStreamD xs)
299------------------------------------------------------------------------------
300-- Transformation Folds
301------------------------------------------------------------------------------
303-- | Right fold to a streaming monad.
305-- > foldrS Stream.cons Stream.nil === id
307-- 'foldrS' can be used to perform stateless stream to stream transformations
308-- like map and filter in general. It can be coupled with a scan to perform
309-- stateful transformations. However, note that the custom map and filter
310-- routines can be much more efficient than this due to better stream fusion.
312-- >>> Stream.toList $ Stream.foldrS Stream.cons Stream.nil $ Stream.fromList [1..5]
315-- Find if any element in the stream is 'True':
317-- >>> 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)
320-- Map (+2) on odd elements and filter out the even elements:
322-- >>> 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)
325-- 'foldrM' can also be represented in terms of 'foldrS', however, the former
326-- is much more efficient:
328-- > foldrM f z s = runIdentityT $ foldrS (\x xs -> lift $ f x (runIdentityT xs)) (lift z) s
332foldrS :: IsStream t => (a -> t m b -> t m b) -> t m b -> t m a -> t m b
336 (\y ys -> toStream $ f y (fromStream ys))
340{-# INLINE foldrSShared #-}
341foldrSShared :: IsStream t => (a -> t m b -> t m b) -> t m b -> t m a -> t m b
345 (\y ys -> toStream $ f y (fromStream ys))
349-- | Right fold to a transformer monad. This is the most general right fold
350-- function. 'foldrS' is a special case of 'foldrT', however 'foldrS'
351-- implementation can be more efficient:
354-- > foldrM f z s = runIdentityT $ foldrT (\x xs -> lift $ f x (runIdentityT xs)) (lift z) s
356-- 'foldrT' can be used to translate streamly streams to other transformer
357-- monads e.g. to a different streaming type.
361foldrT :: (IsStream t, Monad m, Monad (s m), MonadTrans s)
362 => (a -> s m b -> s m b) -> s m b -> t m a -> s m b
363foldrT f z s = S.foldrT f z (toStreamS s)
365------------------------------------------------------------------------------
366-- Transformation by Mapping
367------------------------------------------------------------------------------
371-- mapM f = sequence . map f
374-- Apply a monadic function to each element of the stream and replace it with
375-- the output of the resulting action.
378-- >>> drain $ Stream.mapM putStr $ Stream.fromList ["a", "b", "c"]
382-- drain $ Stream.replicateM 10 (return 1)
383-- & (fromSerial . Stream.mapM (\x -> threadDelay 1000000 >> print x))
389-- > drain $ Stream.replicateM 10 (return 1)
390-- & (fromAsync . Stream.mapM (\x -> threadDelay 1000000 >> print x))
393-- /Concurrent (do not use with 'fromParallel' on infinite streams)/
396{-# INLINE_EARLY mapM #-}
397mapM :: forall t m a b. (IsStream t, MonadAsync m) =>
398 (a -> m b) -> t m a -> t m b
399mapM f = fromStream . K.mapMWith (toConsK (consM @t)) f . toStream
401{-# RULES "mapM serial" mapM = mapMSerial #-}
402{-# INLINE mapMSerial #-}
403mapMSerial :: Monad m => (a -> m b) -> SerialT m a -> SerialT m b
404mapMSerial = Serial.mapM
411-- Replace the elements of a stream of monadic actions with the outputs of
415-- >>> drain $ Stream.sequence $ Stream.fromList [putStr "a", putStr "b", putStrLn "c"]
419-- drain $ Stream.replicateM 3 (return $ threadDelay 1000000 >> print 1)
420-- & (fromSerial . Stream.sequence)
427-- drain $ Stream.replicateM 3 (return $ threadDelay 1000000 >> print 1)
428-- & (fromAsync . Stream.sequence)
436-- /Concurrent (do not use with 'fromParallel' on infinite streams)/
439{-# INLINE sequence #-}
440sequence :: (IsStream t, MonadAsync m) => t m (m a) -> t m a
443------------------------------------------------------------------------------
444-- Mapping side effects
445------------------------------------------------------------------------------
447-- | Tap the data flowing through a stream into a 'Fold'. For example, you may
448-- add a tap to log the contents flowing through the stream. The fold is used
449-- only for effects, its result is discarded.
454-- -----stream m a ---------------stream m a-----
458-- >>> Stream.drain $ Stream.tap (Fold.drainBy print) (Stream.enumerateFromTo 1 2)
462-- Compare with 'trace'.
466tap :: (IsStream t, Monad m) => FL.Fold m a b -> t m a -> t m a
467tap f xs = fromStreamD $ D.tap f (toStreamD xs)
469-- XXX Remove this. It can be expressed in terms of Fold.sampleFromThen.
471-- | @tapOffsetEvery offset n@ taps every @n@th element in the stream
472-- starting at @offset@. @offset@ can be between @0@ and @n - 1@. Offset 0
473-- means start at the first element in the stream. If the offset is outside
474-- this range then @offset `mod` n@ is used as offset.
476-- >>> Stream.drain $ Stream.tapOffsetEvery 0 2 (Fold.rmapM print Fold.toList) $ Stream.enumerateFromTo 0 10
482{-# INLINE tapOffsetEvery #-}
483tapOffsetEvery :: (IsStream t, Monad m)
484 => Int -> Int -> FL.Fold m a b -> t m a -> t m a
485tapOffsetEvery offset n f xs =
486 fromStreamD $ D.tapOffsetEvery offset n f (toStreamD xs)
488-- | Redirect a copy of the stream to a supplied fold and run it concurrently
489-- in an independent thread. The fold may buffer some elements. The buffer size
490-- is determined by the prevailing 'maxBuffer' setting.
495-- -----stream m a ---------------stream m a-----
500-- >>> Stream.drain $ Stream.tapAsync (Fold.drainBy print) (Stream.enumerateFromTo 1 2)
506-- Exceptions from the concurrently running fold are propagated to the current
507-- computation. Note that, because of buffering in the fold, exceptions may be
508-- delayed and may not correspond to the current element being processed in the
509-- parent stream, but we guarantee that before the parent stream stops the tap
510-- finishes and all exceptions from it are drained.
512-- >>> tapAsync f = Stream.tapAsyncK (Stream.fold f . Stream.adapt)
514-- Compare with 'tap'.
517{-# INLINE tapAsync #-}
518tapAsync :: (IsStream t, MonadAsync m) => FL.Fold m a b -> t m a -> t m a
519tapAsync f xs = fromStreamD $ Par.tapAsyncF f (toStreamD xs)
521-- XXX We should keep only tapAsyncK as tapAsync can be implemented in terms
522-- of tapAsyncK and it has better performance. Rename this to tapAsync.
524-- | Like 'tapAsyncF' but uses a stream fold function instead of a 'Fold' type.
527{-# INLINE tapAsyncK #-}
528tapAsyncK :: (IsStream t, MonadAsync m) => (t m a -> m b) -> t m a -> t m a
529tapAsyncK f m = fromStream $ Par.tapAsyncK (f . fromStream) (toStream m)
531-- XXX rename this to tapManyAsync_?
533-- | Concurrently distribute a stream to a collection of fold functions,
534-- discarding the outputs of the folds.
537-- > Stream.drain $ Stream.distributeAsync_ [Stream.mapM_ print, Stream.mapM_ print] (Stream.enumerateFromTo 1 2)
546-- distributeAsync_ = flip (foldr tapAsync)
551{-# INLINE distributeAsync_ #-}
552distributeAsync_ :: (Foldable f, IsStream t, MonadAsync m)
553 => f (t m a -> m b) -> t m a -> t m a
554distributeAsync_ = flip (Prelude.foldr tapAsyncK)
556-- | @pollCounts predicate transform fold stream@ counts those elements in the
557-- stream that pass the @predicate@. The resulting count stream is sent to
558-- another thread which transforms it using @transform@ and then folds it using
559-- @fold@. The thread is automatically cleaned up if the stream stops or
560-- aborts due to exception.
562-- For example, to print the count of elements processed every second:
565-- > Stream.drain $ Stream.pollCounts (const True) (Stream.rollingMap (-) . Stream.delayPost 1) (FLold.drainBy print)
566-- $ Stream.enumerateFrom 0
569-- Note: This may not work correctly on 32-bit machines.
573{-# INLINE pollCounts #-}
575 (IsStream t, MonadAsync m)
577 -> (t m Int -> t m Int)
581pollCounts predicate transf f xs =
583 $ D.pollCounts predicate (toStreamD . transf . fromStreamD) f
586-- | Apply a monadic function to each element flowing through the stream and
587-- discard the results.
590-- >>> Stream.drain $ Stream.trace print (Stream.enumerateFromTo 1 2)
596-- Compare with 'tap'.
600trace :: (IsStream t, MonadAsync m) => (a -> m b) -> t m a -> t m a
601trace f = mapM (\x -> void (f x) >> return x)
603-- | Perform a side effect before yielding each element of the stream and
604-- discard the results.
607-- >>> Stream.drain $ Stream.trace_ (print "got here") (Stream.enumerateFromTo 1 2)
613-- Same as 'interspersePrefix_' but always serial.
619trace_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
620trace_ eff = fromStreamD . D.mapM (\x -> eff >> return x) . toStreamD
622------------------------------------------------------------------------------
623-- Scanning with a Fold
624------------------------------------------------------------------------------
626-- | Scan a stream using the given monadic fold.
628-- >>> Stream.toList $ Stream.takeWhile (< 10) $ Stream.scan Fold.sum (Stream.fromList [1..10])
633scan :: (IsStream t, Monad m) => Fold m a b -> t m a -> t m b
634scan fld m = fromStreamD $ D.scanOnce fld $ toStreamD m
636-- | Like 'scan' but restarts scanning afresh when the scanning fold
640{-# INLINE scanMany #-}
641scanMany :: (IsStream t, Monad m) => Fold m a b -> t m a -> t m b
642scanMany fld m = fromStreamD $ D.scanMany fld $ toStreamD m
644-- | Postscan a stream using the given monadic fold.
646-- The following example extracts the input stream up to a point where the
647-- running average of elements is no more than 10:
649-- >>> import Data.Maybe (fromJust)
650-- >>> let avg = Fold.teeWith (/) Fold.sum (fmap fromIntegral Fold.length)
653-- $ Stream.map (fromJust . fst)
654-- $ Stream.takeWhile (\(_,x) -> x <= 10)
655-- $ Stream.postscan (Fold.tee Fold.last avg) (Stream.enumerateFromTo 1.0 100.0)
657-- [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]
660{-# INLINE postscan #-}
661postscan :: (IsStream t, Monad m) => Fold m a b -> t m a -> t m b
662postscan fld = fromStreamD . D.postscanOnce fld . toStreamD
664------------------------------------------------------------------------------
665-- Scanning - Transformation by Folding
666------------------------------------------------------------------------------
668-- XXX It may be useful to have a version of scan where we can keep the
669-- accumulator independent of the value emitted. So that we do not necessarily
670-- have to keep a value in the accumulator which we are not using. We can pass
671-- an extraction function that will take the accumulator and the current value
672-- of the element and emit the next value in the stream. That will also make it
673-- possible to modify the accumulator after using it. In fact, the step function
674-- can return new accumulator and the value to be emitted. The signature would
675-- be more like mapAccumL. Or we can change the signature of scanx to
678-- | Strict left scan with an extraction function. Like 'scanl'', but applies a
679-- user supplied extraction function (the third argument) at each step. This is
680-- designed to work with the @foldl@ library. The suffix @x@ is a mnemonic for
685-- /Since: 0.7.0 (Monad m constraint)/
686{-# DEPRECATED scanx "Please use scanl followed by map instead." #-}
688scanx :: (IsStream t, Monad m) => (x -> a -> x) -> x -> (x -> b) -> t m a -> t m b
689scanx step begin done = fromStreamS . S.scanlx' step begin done . toStreamS
691-- XXX this needs to be concurrent
692-- XXX because of the use of D.cons for appending, scanlM' has quadratic
693-- complexity when iterated over a stream. We should use StreamK style scanlM'
694-- for linear performance on iteration.
696-- | Like 'scanl'' but with a monadic step function and a monadic seed.
700-- /Since: 0.8.0 (signature change)/
701{-# INLINE scanlM' #-}
702scanlM' :: (IsStream t, Monad m) => (b -> a -> m b) -> m b -> t m a -> t m b
703scanlM' step begin m = fromStreamD $ D.scanlM' step begin $ toStreamD m
705-- XXX because of the use of D.cons for appending, scanl' has quadratic
706-- complexity when iterated over a stream. We should use StreamK style scanlM'
707-- for linear performance on iteration.
709-- | Strict left scan. Like 'map', 'scanl'' too is a one to one transformation,
710-- however it adds an extra element.
713-- >>> Stream.toList $ Stream.scanl' (+) 0 $ fromList [1,2,3,4]
719-- >>> Stream.toList $ Stream.scanl' (flip (:)) [] $ Stream.fromList [1,2,3,4]
720-- [[],[1],[2,1],[3,2,1],[4,3,2,1]]
724-- The output of 'scanl'' is the initial value of the accumulator followed by
725-- all the intermediate steps and the final result of 'foldl''.
727-- By streaming the accumulated state after each fold step, we can share the
728-- state across multiple stages of stream composition. Each stage can modify or
729-- extend the state, do some processing with it and emit it for the next stage,
730-- thus modularizing the stream processing. This can be useful in
731-- stateful or event-driven programming.
733-- Consider the following monolithic example, computing the sum and the product
734-- of the elements in a stream in one go using a @foldl'@:
737-- >>> Stream.foldl' (\(s, p) x -> (s + x, p * x)) (0,1) $ Stream.fromList [1,2,3,4]
742-- Using @scanl'@ we can make it modular by computing the sum in the first
743-- stage and passing it down to the next stage for computing the product:
747-- Stream.foldl' (\(_, p) (s, x) -> (s, p * x)) (0,1)
748-- $ Stream.scanl' (\(s, _) x -> (s + x, x)) (0,1)
749-- $ Stream.fromList [1,2,3,4]
755-- IMPORTANT: 'scanl'' evaluates the accumulator to WHNF. To avoid building
756-- lazy expressions inside the accumulator, it is recommended that a strict
757-- data structure is used for accumulator.
759-- >>> scanl' step z = scan (Fold.foldl' step z)
760-- >>> scanl' f z xs = scanlM' (\a b -> return (f a b)) (return z) xs
761-- >>> scanl' f z xs = z `Stream.cons` postscanl' f z xs
763-- See also: 'usingStateT'
767scanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
768scanl' step z m = fromStreamS $ S.scanl' step z $ toStreamS m
770-- | Like 'scanl'' but does not stream the initial value of the accumulator.
772-- >>> postscanl' step z = postscan (Fold.foldl' step z)
773-- >>> postscanl' f z = postscanlM' (\a b -> return (f a b)) (return z)
774-- >>> postscanl' f z xs = Stream.drop 1 $ Stream.scanl' f z xs
777{-# INLINE postscanl' #-}
778postscanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
779postscanl' step z m = fromStreamD $ D.postscanl' step z $ toStreamD m
781-- XXX prescanl does not sound very useful, enable only if there is a
782-- compelling use case.
784-- | Like scanl' but does not stream the final value of the accumulator.
787{-# INLINE prescanl' #-}
788prescanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
789prescanl' step z m = fromStreamD $ D.prescanl' step z $ toStreamD m
791-- XXX this needs to be concurrent
792-- | Like prescanl' but with a monadic step function and a monadic seed.
795{-# INLINE prescanlM' #-}
796prescanlM' :: (IsStream t, Monad m) => (b -> a -> m b) -> m b -> t m a -> t m b
797prescanlM' step z m = fromStreamD $ D.prescanlM' step z $ toStreamD m
799-- XXX this needs to be concurrent
800-- | Like 'scanl1'' but with a monadic step function.
803{-# INLINE scanl1M' #-}
804scanl1M' :: (IsStream t, Monad m) => (a -> a -> m a) -> t m a -> t m a
805scanl1M' step m = fromStreamD $ D.scanl1M' step $ toStreamD m
807-- | Like 'scanl'' but for a non-empty stream. The first element of the stream
808-- is used as the initial value of the accumulator. Does nothing if the stream
812-- >>> Stream.toList $ Stream.scanl1' (+) $ fromList [1,2,3,4]
818{-# INLINE scanl1' #-}
819scanl1' :: (IsStream t, Monad m) => (a -> a -> a) -> t m a -> t m a
820scanl1' step m = fromStreamD $ D.scanl1' step $ toStreamD m
822------------------------------------------------------------------------------
824------------------------------------------------------------------------------
826-- | Modify a @t m a -> t m a@ stream transformation that accepts a predicate
827-- @(a -> b)@ to accept @((s, a) -> b)@ instead, provided a transformation @t m
828-- a -> t m (s, a)@. Convenient to filter with index or time.
831-- filterWithIndex = with indexed filter
832-- filterWithAbsTime = with timestamped filter
833-- filterWithRelTime = with timeIndexed filter
838with :: forall (t :: (Type -> Type) -> Type -> Type) m a b s. Functor (t m) =>
839 (t m a -> t m (s, a))
840 -> (((s, a) -> b) -> t m (s, a) -> t m (s, a))
841 -> (((s, a) -> b) -> t m a -> t m a)
842with f comb g = fmap snd . comb g . f
844-- | Include only those elements that pass a predicate.
848filter :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m a
849filter p m = fromStreamS $ S.filter p $ toStreamS m
851-- | Same as 'filter' but with a monadic predicate.
854{-# INLINE filterM #-}
855filterM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
856filterM p m = fromStreamD $ D.filterM p $ toStreamD m
858-- | Drop repeated elements that are adjacent to each other using the supplied
859-- comparison function.
861-- @uniq = uniqBy (==)
863-- To strip duplicate path separators:
866-- f x y = x == '/' && x == y
867-- Stream.toList $ Stream.uniqBy f $ Stream.fromList "//a//b"
878uniqBy :: (IsStream t, Monad m, Functor (t m)) =>
879 (a -> a -> Bool) -> t m a -> t m a
880uniqBy eq = catMaybes . rollingMap f
887 Just x -> if x `eq` curr then Nothing else Just curr
889-- | Drop repeated elements that are adjacent to each other.
893uniq :: (Eq a, IsStream t, Monad m) => t m a -> t m a
894uniq = fromStreamD . D.uniq . toStreamD
896-- | Strip all leading and trailing occurrences of an element passing a
897-- predicate and make all other consecutive occurrences uniq.
900-- prune p = dropWhileAround p $ uniqBy (x y -> p x && p y)
904-- > Stream.prune isSpace (Stream.fromList " hello world! ")
914 -- (IsStream t, Monad m, Eq a) =>
915 (a -> Bool) -> t m a -> t m a
916prune = error "Not implemented yet!"
918-- Possible implementation:
920-- Stream.catMaybes . Stream.parseMany (Parser.groupBy (==) Fold.repeated)@
922-- 'Fold.repeated' should return 'Just' when repeated, and 'Nothing' for a
925-- | Emit only repeated elements, once.
928repeated :: -- (IsStream t, Monad m, Eq a) =>
932-- We can have more efficient implementations for nubOrd and nubInt by using
933-- Set and IntSet to find/remove duplication. For Hashable we can use a
934-- hashmap. Use rewrite rules to specialize to more efficient impls.
936-- | Drop repeated elements anywhere in the stream.
938-- /Caution: not scalable for infinite streams/
940-- /See also: nubWindowBy/
945nubBy :: -- (IsStream t, Monad m) =>
946 (a -> a -> Bool) -> t m a -> t m a
947nubBy = undefined -- fromStreamD . D.nubBy . toStreamD
949-- | Drop repeated elements within the specified tumbling window in the stream.
951-- @nubBy = nubWindowBy maxBound@
955{-# INLINE nubWindowBy #-}
956nubWindowBy :: -- (IsStream t, Monad m) =>
957 Int -> (a -> a -> Bool) -> t m a -> t m a
958nubWindowBy = undefined -- fromStreamD . D.nubWithinBy . toStreamD
960-- | Deletes the first occurrence of the element in the stream that satisfies
961-- the given equality predicate.
964-- >>> Stream.toList $ Stream.deleteBy (==) 3 $ Stream.fromList [1,3,3,5]
970{-# INLINE deleteBy #-}
971deleteBy :: (IsStream t, Monad m) => (a -> a -> Bool) -> a -> t m a -> t m a
972deleteBy cmp x m = fromStreamS $ S.deleteBy cmp x (toStreamS m)
974------------------------------------------------------------------------------
976------------------------------------------------------------------------------
978-- XXX We could use 'maxBuffer Block/Drop/Rotate/Sample' instead. However we
979-- may want to have the evaluation rate independent of the sampling rate. To
980-- support that we can decouple evaluation and sampling in independent stages.
981-- The sampling stage would strictly evaluate and sample, the evaluation stage
982-- would control the evaluation rate.
984-- | Evaluate the input stream continuously and keep only the oldest @n@
985-- elements in the buffer, discard the new ones when the buffer is full. When
986-- the output stream is evaluated it consumes the values from the buffer in a
991{-# INLINE sampleOld #-}
992sampleOld :: -- (IsStream t, Monad m) =>
993 Int -> t m a -> t m a
996-- | Evaluate the input stream continuously and keep only the latest @n@
997-- elements in a ring buffer, keep discarding the older ones to make space for
998-- the new ones. When the output stream is evaluated it consumes the values
999-- from the buffer in a FIFO manner.
1003{-# INLINE sampleNew #-}
1004sampleNew :: -- (IsStream t, Monad m) =>
1005 Int -> t m a -> t m a
1006sampleNew = undefined
1008-- | Like 'sampleNew' but samples at uniform intervals to match the consumer
1009-- rate. Note that 'sampleNew' leads to non-uniform sampling depending on the
1014{-# INLINE sampleRate #-}
1015sampleRate :: -- (IsStream t, Monad m) =>
1016 Double -> t m a -> t m a
1017sampleRate = undefined
1019------------------------------------------------------------------------------
1021------------------------------------------------------------------------------
1023-- | Same as 'takeWhile' but with a monadic predicate.
1026{-# INLINE takeWhileM #-}
1027takeWhileM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
1028takeWhileM p m = fromStreamD $ D.takeWhileM p $ toStreamD m
1030-- See the lastN fold for impl hints. Use a Data.Array based ring buffer.
1032-- takeLast n = Stream.concatM . fmap Array.toStream . fold Fold.lastN
1034-- | Take @n@ elements at the end of the stream.
1036-- O(n) space, where n is the number elements taken.
1039{-# INLINE takeLast #-}
1040takeLast :: -- (IsStream t, Monad m) =>
1041 Int -> t m a -> t m a
1042takeLast = undefined -- fromStreamD $ D.takeLast n $ toStreamD m
1044-- | Take time interval @i@ seconds at the end of the stream.
1046-- O(n) space, where n is the number elements taken.
1049{-# INLINE takeLastInterval #-}
1050takeLastInterval :: -- (IsStream t, Monad m) =>
1051 Double -> t m a -> t m a
1052takeLastInterval = undefined -- fromStreamD $ D.takeLast n $ toStreamD m
1054-- | Take all consecutive elements at the end of the stream for which the
1055-- predicate is true.
1057-- O(n) space, where n is the number elements taken.
1060{-# INLINE takeWhileLast #-}
1061takeWhileLast :: -- (IsStream t, Monad m) =>
1062 (a -> Bool) -> t m a -> t m a
1063takeWhileLast = undefined -- fromStreamD $ D.takeWhileLast n $ toStreamD m
1065-- | Like 'takeWhile' and 'takeWhileLast' combined.
1067-- O(n) space, where n is the number elements taken from the end.
1070{-# INLINE takeWhileAround #-}
1071takeWhileAround :: -- (IsStream t, Monad m) =>
1072 (a -> Bool) -> t m a -> t m a
1073takeWhileAround = undefined -- fromStreamD $ D.takeWhileAround n $ toStreamD m
1075-- | @takeInterval duration@ yields stream elements upto specified time
1076-- @duration@. The duration starts when the stream is evaluated for the first
1077-- time, before the first element is yielded. The time duration is checked
1078-- before generating each element, if the duration has expired the stream
1081-- The total time taken in executing the stream is guaranteed to be /at least/
1082-- @duration@, however, because the duration is checked before generating an
1083-- element, the upper bound is indeterminate and depends on the time taken in
1084-- generating and processing the last element.
1086-- No element is yielded if the duration is zero. At least one element is
1087-- yielded if the duration is non-zero.
1091{-# INLINE takeInterval #-}
1092takeInterval ::(MonadIO m, IsStream t, TimeUnit64 d) => d -> t m a -> t m a
1093takeInterval d = fromStreamD . D.takeByTime d . toStreamD
1095-- | Drop elements in the stream as long as the predicate succeeds and then
1096-- take the rest of the stream.
1099{-# INLINE dropWhile #-}
1100dropWhile :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m a
1101dropWhile p m = fromStreamS $ S.dropWhile p $ toStreamS m
1103-- | Same as 'dropWhile' but with a monadic predicate.
1106{-# INLINE dropWhileM #-}
1107dropWhileM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
1108dropWhileM p m = fromStreamD $ D.dropWhileM p $ toStreamD m
1110-- | @dropInterval duration@ drops stream elements until specified @duration@ has
1111-- passed. The duration begins when the stream is evaluated for the first
1112-- time. The time duration is checked /after/ generating a stream element, the
1113-- element is yielded if the duration has expired otherwise it is dropped.
1115-- The time elapsed before starting to generate the first element is /at most/
1116-- @duration@, however, because the duration expiry is checked after the
1117-- element is generated, the lower bound is indeterminate and depends on the
1118-- time taken in generating an element.
1120-- All elements are yielded if the duration is zero.
1124{-# INLINE dropInterval #-}
1125dropInterval ::(MonadIO m, IsStream t, TimeUnit64 d) => d -> t m a -> t m a
1126dropInterval d = fromStreamD . D.dropByTime d . toStreamD
1128-- | Drop @n@ elements at the end of the stream.
1130-- O(n) space, where n is the number elements dropped.
1133{-# INLINE dropLast #-}
1134dropLast :: -- (IsStream t, Monad m) =>
1135 Int -> t m a -> t m a
1136dropLast = undefined -- fromStreamD $ D.dropLast n $ toStreamD m
1138-- | Drop time interval @i@ seconds at the end of the stream.
1140-- O(n) space, where n is the number elements dropped.
1143{-# INLINE dropLastInterval #-}
1144dropLastInterval :: -- (IsStream t, Monad m) =>
1145 Int -> t m a -> t m a
1146dropLastInterval = undefined
1148-- | Drop all consecutive elements at the end of the stream for which the
1149-- predicate is true.
1151-- O(n) space, where n is the number elements dropped.
1154{-# INLINE dropWhileLast #-}
1155dropWhileLast :: -- (IsStream t, Monad m) =>
1156 (a -> Bool) -> t m a -> t m a
1157dropWhileLast = undefined -- fromStreamD $ D.dropWhileLast n $ toStreamD m
1159-- | Like 'dropWhile' and 'dropWhileLast' combined.
1161-- O(n) space, where n is the number elements dropped from the end.
1164{-# INLINE dropWhileAround #-}
1165dropWhileAround :: -- (IsStream t, Monad m) =>
1166 (a -> Bool) -> t m a -> t m a
1167dropWhileAround = undefined -- fromStreamD $ D.dropWhileAround n $ toStreamD m
1169------------------------------------------------------------------------------
1170-- Inserting Elements
1171------------------------------------------------------------------------------
1173-- | @insertBy cmp elem stream@ inserts @elem@ before the first element in
1174-- @stream@ that is less than @elem@ when compared using @cmp@.
1177-- insertBy cmp x = 'mergeBy' cmp ('fromPure' x)
1181-- >>> Stream.toList $ Stream.insertBy compare 2 $ Stream.fromList [1,3,5]
1187{-# INLINE insertBy #-}
1189 (IsStream t, Monad m) => (a -> a -> Ordering) -> a -> t m a -> t m a
1190insertBy cmp x m = fromStreamS $ S.insertBy cmp x (toStreamS m)
1192-- | Insert a pure value between successive elements of a stream.
1194-- >>> Stream.toList $ Stream.intersperse ',' $ Stream.fromList "hello"
1198{-# INLINE intersperse #-}
1199intersperse :: (IsStream t, MonadAsync m) => a -> t m a -> t m a
1200intersperse a = fromStreamS . S.intersperse a . toStreamS
1202-- | Insert a side effect before consuming an element of a stream except the
1205-- >>> Stream.drain $ Stream.trace putChar $ Stream.intersperseM_ (putChar '.') $ Stream.fromList "hello"
1209{-# INLINE intersperseM_ #-}
1210intersperseM_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
1211intersperseM_ m = fromStreamD . D.intersperseM_ m . toStreamD
1213-- | Intersperse a monadic action into the input stream after every @n@
1217-- > Stream.toList $ Stream.intersperseBySpan 2 (return ',') $ Stream.fromList "hello"
1223{-# INLINE intersperseBySpan #-}
1224intersperseBySpan :: -- IsStream t =>
1225 Int -> m a -> t m a -> t m a
1226intersperseBySpan _n _f _xs = undefined
1228-- | Insert an effect and its output after consuming an element of a stream.
1230-- >>> Stream.toList $ Stream.trace putChar $ intersperseSuffix (putChar '.' >> return ',') $ Stream.fromList "hello"
1231-- h.,e.,l.,l.,o.,"h,e,l,l,o,"
1234{-# INLINE intersperseSuffix #-}
1235intersperseSuffix :: (IsStream t, Monad m) => m a -> t m a -> t m a
1236intersperseSuffix m = fromStreamD . D.intersperseSuffix m . toStreamD
1238-- | Insert a side effect after consuming an element of a stream.
1241-- >>> Stream.mapM_ putChar $ Stream.intersperseSuffix_ (threadDelay 1000000) $ Stream.fromList "hello"
1248{-# INLINE intersperseSuffix_ #-}
1249intersperseSuffix_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
1250intersperseSuffix_ m = fromStreamD . D.intersperseSuffix_ m . toStreamD
1252-- XXX Use an offset argument, like tapOffsetEvery
1254-- | Like 'intersperseSuffix' but intersperses an effectful action into the
1255-- input stream after every @n@ elements and after the last element.
1257-- >>> Stream.toList $ Stream.intersperseSuffixBySpan 2 (return ',') $ Stream.fromList "hello"
1262{-# INLINE intersperseSuffixBySpan #-}
1263intersperseSuffixBySpan :: (IsStream t, Monad m)
1264 => Int -> m a -> t m a -> t m a
1265intersperseSuffixBySpan n eff =
1266 fromStreamD . D.intersperseSuffixBySpan n eff . toStreamD
1268-- | Insert a side effect before consuming an element of a stream.
1270-- >>> Stream.toList $ Stream.trace putChar $ Stream.interspersePrefix_ (putChar '.' >> return ',') $ Stream.fromList "hello"
1273-- Same as 'trace_' but may be concurrent.
1279{-# INLINE interspersePrefix_ #-}
1280interspersePrefix_ :: (IsStream t, MonadAsync m) => m b -> t m a -> t m a
1281interspersePrefix_ m = mapM (\x -> void m >> return x)
1283------------------------------------------------------------------------------
1285------------------------------------------------------------------------------
1287-- Note: delay must be serial.
1289-- | Introduce a delay of specified seconds before consuming an element of the
1290-- stream except the first one.
1292-- >>> Stream.mapM_ print $ Stream.timestamped $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
1293-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),1)
1294-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),2)
1295-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),3)
1300delay :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
1301delay n = intersperseM_ $ liftIO $ threadDelay $ round $ n * 1000000
1303-- Note: delay must be serial.
1305-- | Introduce a delay of specified seconds after consuming an element of a
1308-- >>> Stream.mapM_ print $ Stream.timestamped $ Stream.delayPost 1 $ Stream.enumerateFromTo 1 3
1309-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),1)
1310-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),2)
1311-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),3)
1315{-# INLINE delayPost #-}
1316delayPost :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
1317delayPost n = intersperseSuffix_ $ liftIO $ threadDelay $ round $ n * 1000000
1319-- Note: delay must be serial, that's why 'trace_' is used.
1321-- | Introduce a delay of specified seconds before consuming an element of a
1324-- >>> Stream.mapM_ print $ Stream.timestamped $ Stream.delayPre 1 $ Stream.enumerateFromTo 1 3
1325-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),1)
1326-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),2)
1327-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),3)
1331{-# INLINE delayPre #-}
1332delayPre :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
1333delayPre n = trace_ $ liftIO $ threadDelay $ round $ n * 1000000
1335------------------------------------------------------------------------------
1336-- Reorder in sequence
1337------------------------------------------------------------------------------
1339-- | Buffer until the next element in sequence arrives. The function argument
1340-- determines the difference in sequence numbers. This could be useful in
1341-- implementing sequenced streams, for example, TCP reassembly.
1345{-# INLINE reassembleBy #-}
1347 :: -- (IsStream t, Monad m) =>
1352reassembleBy = undefined
1354------------------------------------------------------------------------------
1356------------------------------------------------------------------------------
1359-- > indexed = Stream.postscanl' (\(i, _) x -> (i + 1, x)) (-1,undefined)
1360-- > indexed = Stream.zipWith (,) (Stream.enumerateFrom 0)
1362-- Pair each element in a stream with its index, starting from index 0.
1364-- >>> Stream.toList $ Stream.indexed $ Stream.fromList "hello"
1365-- [(0,'h'),(1,'e'),(2,'l'),(3,'l'),(4,'o')]
1368{-# INLINE indexed #-}
1369indexed :: (IsStream t, Monad m) => t m a -> t m (Int, a)
1370indexed = fromStreamD . D.indexed . toStreamD
1373-- > indexedR n = Stream.postscanl' (\(i, _) x -> (i - 1, x)) (n + 1,undefined)
1374-- > indexedR n = Stream.zipWith (,) (Stream.enumerateFromThen n (n - 1))
1376-- Pair each element in a stream with its index, starting from the
1377-- given index @n@ and counting down.
1379-- >>> Stream.toList $ Stream.indexedR 10 $ Stream.fromList "hello"
1380-- [(10,'h'),(9,'e'),(8,'l'),(7,'l'),(6,'o')]
1383{-# INLINE indexedR #-}
1384indexedR :: (IsStream t, Monad m) => Int -> t m a -> t m (Int, a)
1385indexedR n = fromStreamD . D.indexedR n . toStreamD
1387-------------------------------------------------------------------------------
1389-------------------------------------------------------------------------------
1391-- Note: The timestamp stream must be the second stream in the zip so that the
1392-- timestamp is generated after generating the stream element and not before.
1393-- If we do not do that then the following example will generate the same
1394-- timestamp for first two elements:
1396-- Stream.mapM_ print $ Stream.timestamped $ Stream.delay $ Stream.enumerateFromTo 1 3
1398-- | Pair each element in a stream with an absolute timestamp, using a clock of
1399-- specified granularity. The timestamp is generated just before the element
1402-- >>> Stream.mapM_ print $ Stream.timestampWith 0.01 $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
1403-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),1)
1404-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),2)
1405-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),3)
1409{-# INLINE timestampWith #-}
1410timestampWith :: (IsStream t, MonadAsync m, Functor (t m))
1411 => Double -> t m a -> t m (AbsTime, a)
1412timestampWith g stream = zipWith (flip (,)) stream (absTimesWith g)
1414-- TBD: check performance vs a custom implementation without using zipWith.
1418{-# INLINE timestamped #-}
1419timestamped :: (IsStream t, MonadAsync m, Functor (t m))
1420 => t m a -> t m (AbsTime, a)
1421timestamped = timestampWith 0.01
1423-- | Pair each element in a stream with relative times starting from 0, using a
1424-- clock with the specified granularity. The time is measured just before the
1425-- element is consumed.
1427-- >>> Stream.mapM_ print $ Stream.timeIndexWith 0.01 $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
1428-- (RelTime64 (NanoSecond64 ...),1)
1429-- (RelTime64 (NanoSecond64 ...),2)
1430-- (RelTime64 (NanoSecond64 ...),3)
1434{-# INLINE timeIndexWith #-}
1435timeIndexWith :: (IsStream t, MonadAsync m, Functor (t m))
1436 => Double -> t m a -> t m (RelTime64, a)
1437timeIndexWith g stream = zipWith (flip (,)) stream (relTimesWith g)
1439-- | Pair each element in a stream with relative times starting from 0, using a
1440-- 10 ms granularity clock. The time is measured just before the element is
1443-- >>> Stream.mapM_ print $ Stream.timeIndexed $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
1444-- (RelTime64 (NanoSecond64 ...),1)
1445-- (RelTime64 (NanoSecond64 ...),2)
1446-- (RelTime64 (NanoSecond64 ...),3)
1450{-# INLINE timeIndexed #-}
1451timeIndexed :: (IsStream t, MonadAsync m, Functor (t m))
1452 => t m a -> t m (RelTime64, a)
1453timeIndexed = timeIndexWith 0.01
1455------------------------------------------------------------------------------
1457------------------------------------------------------------------------------
1459-- | Find all the indices where the value of the element in the stream is equal
1460-- to the given value.
1462-- > elemIndices a = findIndices (== a)
1465{-# INLINE elemIndices #-}
1466elemIndices :: (IsStream t, Eq a, Monad m) => a -> t m a -> t m Int
1467elemIndices a = findIndices (== a)
1469------------------------------------------------------------------------------
1471------------------------------------------------------------------------------
1473-- XXX this is not a one-to-one map so calling it map may not be right.
1474-- We can perhaps call it zipWithTail or rollWith.
1476-- | Apply a function on every two successive elements of a stream. The first
1477-- argument of the map function is the previous element and the second argument
1478-- is the current element. When the current element is the first element, the
1479-- previous element is 'Nothing'.
1483{-# INLINE rollingMap #-}
1484rollingMap :: (IsStream t, Monad m) => (Maybe a -> a -> b) -> t m a -> t m b
1485rollingMap f m = fromStreamD $ D.rollingMap f $ toStreamD m
1487-- | Like 'rollingMap' but with an effectful map function.
1491{-# INLINE rollingMapM #-}
1492rollingMapM :: (IsStream t, Monad m) => (Maybe a -> a -> m b) -> t m a -> t m b
1493rollingMapM f m = fromStreamD $ D.rollingMapM f $ toStreamD m
1495-- | Like 'rollingMap' but requires at least two elements in the stream,
1496-- returns an empty stream otherwise.
1498-- This is the stream equivalent of the list idiom @zipWith f xs (tail xs)@.
1502{-# INLINE rollingMap2 #-}
1503rollingMap2 :: (IsStream t, Monad m) => (a -> a -> b) -> t m a -> t m b
1504rollingMap2 f m = fromStreamD $ D.rollingMap2 f $ toStreamD m
1506------------------------------------------------------------------------------
1508------------------------------------------------------------------------------
1510-- | Map a 'Maybe' returning function to a stream, filter out the 'Nothing'
1511-- elements, and return a stream of values extracted from 'Just'.
1516-- mapMaybe f = Stream.map 'fromJust' . Stream.filter 'isJust' . Stream.map f
1520{-# INLINE mapMaybe #-}
1521mapMaybe :: (IsStream t, Monad m) => (a -> Maybe b) -> t m a -> t m b
1522mapMaybe f m = fromStreamS $ S.mapMaybe f $ toStreamS m
1524-- | Like 'mapMaybe' but maps a monadic function.
1529-- mapMaybeM f = Stream.map 'fromJust' . Stream.filter 'isJust' . Stream.mapM f
1532-- /Concurrent (do not use with 'fromParallel' on infinite streams)/
1535{-# INLINE_EARLY mapMaybeM #-}
1536mapMaybeM :: (IsStream t, MonadAsync m, Functor (t m))
1537 => (a -> m (Maybe b)) -> t m a -> t m b
1538mapMaybeM f = fmap fromJust . filter isJust . mapM f
1540{-# RULES "mapMaybeM serial" mapMaybeM = mapMaybeMSerial #-}
1541{-# INLINE mapMaybeMSerial #-}
1542mapMaybeMSerial :: Monad m => (a -> m (Maybe b)) -> SerialT m a -> SerialT m b
1543mapMaybeMSerial f m = fromStreamD $ D.mapMaybeM f $ toStreamD m
1545-- | In a stream of 'Maybe's, discard 'Nothing's and unwrap 'Just's.
1549{-# INLINE catMaybes #-}
1550catMaybes :: (IsStream t, Monad m, Functor (t m)) => t m (Maybe a) -> t m a
1551catMaybes = fmap fromJust . filter isJust
1553------------------------------------------------------------------------------
1555------------------------------------------------------------------------------
1557-- | Discard 'Right's and unwrap 'Left's in an 'Either' stream.
1562lefts :: (IsStream t, Monad m, Functor (t m)) => t m (Either a b) -> t m a
1563lefts = fmap (fromLeft undefined) . filter isLeft
1565-- | Discard 'Left's and unwrap 'Right's in an 'Either' stream.
1569{-# INLINE rights #-}
1570rights :: (IsStream t, Monad m, Functor (t m)) => t m (Either a b) -> t m b
1571rights = fmap (fromRight undefined) . filter isRight
1573-- | Remove the either wrapper and flatten both lefts and as well as rights in
1574-- the output stream.
1579both :: Functor (t m) => t m (Either a a) -> t m a
1580both = fmap (either id id)
1582------------------------------------------------------------------------------
1583-- Concurrent Application
1584------------------------------------------------------------------------------
1586-- | Parallel transform application operator; applies a stream transformation
1587-- function @t m a -> t m b@ to a stream @t m a@ concurrently; the input stream
1588-- is evaluated asynchronously in an independent thread yielding elements to a
1589-- buffer and the transformation function runs in another thread consuming the
1590-- input from the buffer. '|$' is just like regular function application
1591-- operator '$' except that it is concurrent.
1593-- If you read the signature as @(t m a -> t m b) -> (t m a -> t m b)@ you can
1594-- look at it as a transformation that converts a transform function to a
1595-- buffered concurrent transform function.
1597-- The following code prints a value every second even though each stage adds a
1603-- Stream.mapM (\x -> threadDelay 1000000 >> print x)
1604-- |$ Stream.replicateM 3 (threadDelay 1000000 >> return 1)
1612-- /Since: 0.3.0 ("Streamly")/
1616(|$) :: (IsStream t, MonadAsync m) => (t m a -> t m b) -> (t m a -> t m b)
1617-- (|$) f = f . mkAsync
1618(|$) f = f . mkParallel
1626{-# INLINE applyAsync #-}
1627applyAsync :: (IsStream t, MonadAsync m)
1628 => (t m a -> t m b) -> (t m a -> t m b)
1631-- | Same as '|$' but with arguments reversed.
1637-- /Since: 0.3.0 ("Streamly")/
1641(|&) :: (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