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.
39 -- * Scanning By 'Fold'
44 -- | Left scans. Stateful, mostly one-to-one maps.
55 -- XXX Once we have pipes the contravariant transformations can be
56 -- represented by attaching pipes before a transformation.
69 -- | Produce a subset of the stream using criteria based on the values of
70 -- the elements. We can use a concatMap and scan for filtering but these
71 -- combinators are more efficient and convenient.
85 -- | Produce a subset of the stream trimmed at ends.
104 -- * Inserting Elements
105 -- | Produce a superset of the stream. This is the opposite of
106 -- filtering/sampling. We can always use concatMap and scan for inserting
107 -- but these combinators are more efficient and convenient.
109 -- Element agnostic (Opposite of sampling)
111 , intersperseM -- XXX naming
115 , intersperseSuffixBySpan
118 -- , interspersePrefix
119 -- , interspersePrefixBySpan
121 -- * Inserting Side Effects/Time
122 , intersperseM_ -- XXX naming
129 -- * Element Aware Insertion
130 -- | Opposite of filtering
132 -- , intersperseByBefore
133 -- , intersperseByAfter
140 -- * Position Indexing
147 -- , timestampedR -- timer
152 , findIndices -- XXX indicesBy
153 , elemIndices -- XXX indicesOf
156 -- | Map using the previous element.
162 -- Move these to Streamly.Data.Maybe.Stream?
163 , catMaybes -- XXX justs (like lefts/rights)
168 -- Move these to Streamly.Data.Either.Stream?
173 -- * Concurrent Evaluation
174 -- ** Concurrent Pipelines
175 -- | Run streaming stages concurrently.
183 -- ** Concurrency Control
186 -- ** Buffering and Sampling
187 -- | Evaluate strictly using a buffer of results. When the buffer becomes
188 -- full we can block, drop the new elements, drop the oldest element and
189 -- insert the new at the end or keep dropping elements uniformly to match
190 -- the rate of the consumer.
197 -- | Evaluate the stream at uniform intervals to maintain a specified
216import Control.Concurrent (threadDelay)
217import Control.Monad (void)
218import Control.Monad.Catch (MonadCatch)
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
248import Streamly.Internal.Control.Concurrent (MonadAsync)
249import Streamly.Internal.Data.Stream.IsStream.Type
250 (IsStream(..), fromStreamS, toStreamS, fromStreamD, toStreamD, toConsK)
251import Streamly.Internal.Data.Stream.Serial (SerialT)
252import Streamly.Internal.Data.SVar (Rate(..))
253import Streamly.Internal.Data.Time.Units (TimeUnit64, AbsTime, RelTime64)
255import qualified Streamly.Internal.Data.Fold as FL
256import qualified Streamly.Internal.Data.Stream.Parallel as Par
257import qualified Streamly.Internal.Data.Stream.Serial as Serial
258import qualified Streamly.Internal.Data.Stream.StreamD as D
259import qualified Streamly.Internal.Data.Stream.StreamK.Type as K
260#ifdef USE_STREAMK_ONLY
261import qualified Streamly.Internal.Data.Stream.StreamK as S
263import qualified Streamly.Internal.Data.Stream.StreamD as S
265import qualified Prelude
268 ( filter, drop, dropWhile, take, takeWhile, foldr, map, mapM, sequence
269 , reverse, foldr1 , scanl, scanl1, zipWith)
274-- >>> import Control.Concurrent (threadDelay)
275-- >>> import Data.Function ((&))
276-- >>> import Streamly.Prelude ((|$))
277-- >>> import Prelude hiding ( filter, drop, dropWhile, take, takeWhile, foldr, map, mapM, sequence, reverse, foldr1 , scanl, scanl1)
278-- >>> import qualified Streamly.Prelude as Stream
279-- >>> import Streamly.Internal.Data.Stream.IsStream as Stream
280-- >>> import qualified Streamly.Data.Fold as Fold
281-- >>> import qualified Streamly.Internal.Data.Fold as Fold
282-- >>> import System.IO (stdout, hSetBuffering, BufferMode(LineBuffering))
284-- >>> hSetBuffering stdout LineBuffering
286------------------------------------------------------------------------------
288------------------------------------------------------------------------------
290-- | Use a 'Pipe' to transform a stream.
294{-# INLINE transform #-}
295transform :: (IsStream t, Monad m) => Pipe m a b -> t m a -> t m b
296transform pipe xs = fromStreamD $ D.transform pipe (toStreamD xs)
298------------------------------------------------------------------------------
299-- Transformation Folds
300------------------------------------------------------------------------------
302-- | Right fold to a streaming monad.
304-- > foldrS Stream.cons Stream.nil === id
306-- 'foldrS' can be used to perform stateless stream to stream transformations
307-- like map and filter in general. It can be coupled with a scan to perform
308-- stateful transformations. However, note that the custom map and filter
309-- routines can be much more efficient than this due to better stream fusion.
311-- >>> Stream.toList $ Stream.foldrS Stream.cons Stream.nil $ Stream.fromList [1..5]
314-- Find if any element in the stream is 'True':
316-- >>> Stream.toList $ Stream.foldrS (\x xs -> if odd x then return True else xs) (return False) $ (Stream.fromList (2:4:5:undefined) :: Stream.SerialT IO Int)
319-- Map (+2) on odd elements and filter out the even elements:
321-- >>> Stream.toList $ Stream.foldrS (\x xs -> if odd x then (x + 2) `Stream.cons` xs else xs) Stream.nil $ (Stream.fromList [1..5] :: Stream.SerialT IO Int)
324-- 'foldrM' can also be represented in terms of 'foldrS', however, the former
325-- is much more efficient:
327-- > foldrM f z s = runIdentityT $ foldrS (\x xs -> lift $ f x (runIdentityT xs)) (lift z) s
331foldrS :: IsStream t => (a -> t m b -> t m b) -> t m b -> t m a -> t m b
335 (\y ys -> toStream $ f y (fromStream ys))
339{-# INLINE foldrSShared #-}
340foldrSShared :: IsStream t => (a -> t m b -> t m b) -> t m b -> t m a -> t m b
344 (\y ys -> toStream $ f y (fromStream ys))
348-- | Right fold to a transformer monad. This is the most general right fold
349-- function. 'foldrS' is a special case of 'foldrT', however 'foldrS'
350-- implementation can be more efficient:
353-- > foldrM f z s = runIdentityT $ foldrT (\x xs -> lift $ f x (runIdentityT xs)) (lift z) s
355-- 'foldrT' can be used to translate streamly streams to other transformer
356-- monads e.g. to a different streaming type.
360foldrT :: (IsStream t, Monad m, Monad (s m), MonadTrans s)
361 => (a -> s m b -> s m b) -> s m b -> t m a -> s m b
362foldrT f z s = S.foldrT f z (toStreamS s)
364------------------------------------------------------------------------------
365-- Transformation by Mapping
366------------------------------------------------------------------------------
370-- mapM f = sequence . map f
373-- Apply a monadic function to each element of the stream and replace it with
374-- the output of the resulting action.
377-- >>> drain $ Stream.mapM putStr $ Stream.fromList ["a", "b", "c"]
381-- drain $ Stream.replicateM 10 (return 1)
382-- & (fromSerial . Stream.mapM (\x -> threadDelay 1000000 >> print x))
388-- > drain $ Stream.replicateM 10 (return 1)
389-- & (fromAsync . Stream.mapM (\x -> threadDelay 1000000 >> print x))
392-- /Concurrent (do not use with 'fromParallel' on infinite streams)/
395{-# INLINE_EARLY mapM #-}
396mapM :: forall t m a b. (IsStream t, MonadAsync m) =>
397 (a -> m b) -> t m a -> t m b
398mapM f = fromStream . K.mapMWith (toConsK (consM @t)) f . toStream
400{-# RULES "mapM serial" mapM = mapMSerial #-}
401{-# INLINE mapMSerial #-}
402mapMSerial :: Monad m => (a -> m b) -> SerialT m a -> SerialT m b
403mapMSerial = Serial.mapM
410-- Replace the elements of a stream of monadic actions with the outputs of
414-- >>> drain $ Stream.sequence $ Stream.fromList [putStr "a", putStr "b", putStrLn "c"]
418-- drain $ Stream.replicateM 3 (return $ threadDelay 1000000 >> print 1)
419-- & (fromSerial . Stream.sequence)
426-- drain $ Stream.replicateM 3 (return $ threadDelay 1000000 >> print 1)
427-- & (fromAsync . Stream.sequence)
435-- /Concurrent (do not use with 'fromParallel' on infinite streams)/
438{-# INLINE sequence #-}
439sequence :: (IsStream t, MonadAsync m) => t m (m a) -> t m a
442------------------------------------------------------------------------------
443-- Mapping side effects
444------------------------------------------------------------------------------
446-- | Tap the data flowing through a stream into a 'Fold'. For example, you may
447-- add a tap to log the contents flowing through the stream. The fold is used
448-- only for effects, its result is discarded.
453-- -----stream m a ---------------stream m a-----
457-- >>> Stream.drain $ Stream.tap (Fold.drainBy print) (Stream.enumerateFromTo 1 2)
461-- Compare with 'trace'.
465tap :: (IsStream t, Monad m) => FL.Fold m a b -> t m a -> t m a
466tap f xs = fromStreamD $ D.tap f (toStreamD xs)
468-- XXX Remove this. It can be expressed in terms of Fold.sampleFromThen.
470-- | @tapOffsetEvery offset n@ taps every @n@th element in the stream
471-- starting at @offset@. @offset@ can be between @0@ and @n - 1@. Offset 0
472-- means start at the first element in the stream. If the offset is outside
473-- this range then @offset `mod` n@ is used as offset.
475-- >>> Stream.drain $ Stream.tapOffsetEvery 0 2 (Fold.rmapM print Fold.toList) $ Stream.enumerateFromTo 0 10
481{-# INLINE tapOffsetEvery #-}
482tapOffsetEvery :: (IsStream t, Monad m)
483 => Int -> Int -> FL.Fold m a b -> t m a -> t m a
484tapOffsetEvery offset n f xs =
485 fromStreamD $ D.tapOffsetEvery offset n f (toStreamD xs)
487-- | Redirect a copy of the stream to a supplied fold and run it concurrently
488-- in an independent thread. The fold may buffer some elements. The buffer size
489-- is determined by the prevailing 'maxBuffer' setting.
494-- -----stream m a ---------------stream m a-----
499-- >>> Stream.drain $ Stream.tapAsync (Fold.drainBy print) (Stream.enumerateFromTo 1 2)
505-- Exceptions from the concurrently running fold are propagated to the current
506-- computation. Note that, because of buffering in the fold, exceptions may be
507-- delayed and may not correspond to the current element being processed in the
508-- parent stream, but we guarantee that before the parent stream stops the tap
509-- finishes and all exceptions from it are drained.
512-- Compare with 'tap'.
515{-# INLINE tapAsync #-}
516tapAsync :: (IsStream t, MonadAsync m) => FL.Fold m a b -> t m a -> t m a
517tapAsync f xs = fromStreamD $ Par.tapAsyncF f (toStreamD xs)
519-- | Redirect a copy of the stream to a supplied fold and run it concurrently
520-- in an independent thread. The fold may buffer some elements. The buffer size
521-- is determined by the prevailing 'Streamly.Prelude.maxBuffer' setting.
526-- -----stream m a ---------------stream m a-----
531-- > S.drain $ S.tapAsync (S.mapM_ print) (S.enumerateFromTo 1 2)
536-- Exceptions from the concurrently running fold are propagated to the current
537-- computation. Note that, because of buffering in the fold, exceptions may be
538-- delayed and may not correspond to the current element being processed in the
539-- parent stream, but we guarantee that before the parent stream stops the tap
540-- finishes and all exceptions from it are drained.
543-- Compare with 'tap'.
546{-# INLINE tapAsyncK #-}
547tapAsyncK :: (IsStream t, MonadAsync m) => (t m a -> m b) -> t m a -> t m a
548tapAsyncK f m = fromStream $ Par.tapAsyncK (f . fromStream) (toStream m)
550-- | Concurrently distribute a stream to a collection of fold functions,
551-- discarding the outputs of the folds.
554-- > Stream.drain $ Stream.distributeAsync_ [Stream.mapM_ print, Stream.mapM_ print] (Stream.enumerateFromTo 1 2)
563-- distributeAsync_ = flip (foldr tapAsync)
568{-# INLINE distributeAsync_ #-}
569distributeAsync_ :: (Foldable f, IsStream t, MonadAsync m)
570 => f (t m a -> m b) -> t m a -> t m a
571distributeAsync_ = flip (Prelude.foldr tapAsyncK)
573-- | @pollCounts predicate transform fold stream@ counts those elements in the
574-- stream that pass the @predicate@. The resulting count stream is sent to
575-- another thread which transforms it using @transform@ and then folds it using
576-- @fold@. The thread is automatically cleaned up if the stream stops or
577-- aborts due to exception.
579-- For example, to print the count of elements processed every second:
582-- > Stream.drain $ Stream.pollCounts (const True) (Stream.rollingMap (-) . Stream.delayPost 1) (FLold.drainBy print)
583-- $ Stream.enumerateFrom 0
586-- Note: This may not work correctly on 32-bit machines.
590{-# INLINE pollCounts #-}
592 (IsStream t, MonadAsync m)
594 -> (t m Int -> t m Int)
598pollCounts predicate transf f xs =
600 $ D.pollCounts predicate (toStreamD . transf . fromStreamD) f
603-- | Calls the supplied function with the number of elements consumed
604-- every @n@ seconds. The given function is run in a separate thread
605-- until the end of the stream. In case there is an exception in the
606-- stream the thread is killed during the next major GC.
608-- Note: The action is not guaranteed to run if the main thread exits.
611-- > delay n = threadDelay (round $ n * 1000000) >> return n
612-- > Stream.toList $ Stream.tapRate 2 (\n -> print $ show n ++ " elements processed") (delay 1 Stream.|: delay 0.5 Stream.|: delay 0.5 Stream.|: Stream.nil)
613-- "2 elements processed"
615-- "1 elements processed"
618-- Note: This may not work correctly on 32-bit machines.
621{-# INLINE tapRate #-}
623 (IsStream t, MonadAsync m, MonadCatch m)
628tapRate n f xs = fromStreamD $ D.tapRate n f $ toStreamD xs
630-- | Apply a monadic function to each element flowing through the stream and
631-- discard the results.
634-- >>> Stream.drain $ Stream.trace print (Stream.enumerateFromTo 1 2)
640-- Compare with 'tap'.
644trace :: (IsStream t, MonadAsync m) => (a -> m b) -> t m a -> t m a
645trace f = mapM (\x -> void (f x) >> return x)
647-- | Perform a side effect before yielding each element of the stream and
648-- discard the results.
651-- >>> Stream.drain $ Stream.trace_ (print "got here") (Stream.enumerateFromTo 1 2)
657-- Same as 'interspersePrefix_' but always serial.
663trace_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
664trace_ eff = fromStreamD . D.mapM (\x -> eff >> return x) . toStreamD
666------------------------------------------------------------------------------
667-- Scanning with a Fold
668------------------------------------------------------------------------------
670-- | Scan a stream using the given monadic fold.
672-- >>> Stream.toList $ Stream.takeWhile (< 10) $ Stream.scan Fold.sum (Stream.fromList [1..10])
677scan :: (IsStream t, Monad m) => Fold m a b -> t m a -> t m b
679scan fld m = fromStreamD $ D.scanOnce fld $ toStreamD m
681-- | Postscan a stream using the given monadic fold.
683-- The following example extracts the input stream up to a point where the
684-- running average of elements is no more than 10:
686-- >>> import Data.Maybe (fromJust)
687-- >>> let avg = Fold.teeWith (/) Fold.sum (fmap fromIntegral Fold.length)
690-- $ Stream.map (fromJust . fst)
691-- $ Stream.takeWhile (\(_,x) -> x <= 10)
692-- $ Stream.postscan (Fold.tee Fold.last avg) (Stream.enumerateFromTo 1.0 100.0)
694-- [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]
697{-# INLINE postscan #-}
698postscan :: (IsStream t, Monad m) => Fold m a b -> t m a -> t m b
699postscan fld = fromStreamD . D.postscanOnce fld . toStreamD
701------------------------------------------------------------------------------
702-- Scanning - Transformation by Folding
703------------------------------------------------------------------------------
705-- XXX It may be useful to have a version of scan where we can keep the
706-- accumulator independent of the value emitted. So that we do not necessarily
707-- have to keep a value in the accumulator which we are not using. We can pass
708-- an extraction function that will take the accumulator and the current value
709-- of the element and emit the next value in the stream. That will also make it
710-- possible to modify the accumulator after using it. In fact, the step function
711-- can return new accumulator and the value to be emitted. The signature would
712-- be more like mapAccumL. Or we can change the signature of scanx to
715-- | Strict left scan with an extraction function. Like 'scanl'', but applies a
716-- user supplied extraction function (the third argument) at each step. This is
717-- designed to work with the @foldl@ library. The suffix @x@ is a mnemonic for
722-- /Since: 0.7.0 (Monad m constraint)/
723{-# DEPRECATED scanx "Please use scanl followed by map instead." #-}
725scanx :: (IsStream t, Monad m) => (x -> a -> x) -> x -> (x -> b) -> t m a -> t m b
726scanx step begin done = fromStreamS . S.scanlx' step begin done . toStreamS
728-- XXX this needs to be concurrent
729-- XXX because of the use of D.cons for appending, scanlM' has quadratic
730-- complexity when iterated over a stream. We should use StreamK style scanlM'
731-- for linear performance on iteration.
733-- | Like 'scanl'' but with a monadic step function and a monadic seed.
737-- /Since: 0.8.0 (signature change)/
738{-# INLINE scanlM' #-}
739scanlM' :: (IsStream t, Monad m) => (b -> a -> m b) -> m b -> t m a -> t m b
740scanlM' step begin m = fromStreamD $ D.scanlM' step begin $ toStreamD m
742-- XXX because of the use of D.cons for appending, scanl' has quadratic
743-- complexity when iterated over a stream. We should use StreamK style scanlM'
744-- for linear performance on iteration.
746-- | Strict left scan. Like 'map', 'scanl'' too is a one to one transformation,
747-- however it adds an extra element.
750-- >>> Stream.toList $ Stream.scanl' (+) 0 $ fromList [1,2,3,4]
756-- >>> Stream.toList $ Stream.scanl' (flip (:)) [] $ Stream.fromList [1,2,3,4]
757-- [[],[1],[2,1],[3,2,1],[4,3,2,1]]
761-- The output of 'scanl'' is the initial value of the accumulator followed by
762-- all the intermediate steps and the final result of 'foldl''.
764-- By streaming the accumulated state after each fold step, we can share the
765-- state across multiple stages of stream composition. Each stage can modify or
766-- extend the state, do some processing with it and emit it for the next stage,
767-- thus modularizing the stream processing. This can be useful in
768-- stateful or event-driven programming.
770-- Consider the following monolithic example, computing the sum and the product
771-- of the elements in a stream in one go using a @foldl'@:
774-- >>> Stream.foldl' (\(s, p) x -> (s + x, p * x)) (0,1) $ Stream.fromList [1,2,3,4]
779-- Using @scanl'@ we can make it modular by computing the sum in the first
780-- stage and passing it down to the next stage for computing the product:
784-- Stream.foldl' (\(_, p) (s, x) -> (s, p * x)) (0,1)
785-- $ Stream.scanl' (\(s, _) x -> (s + x, x)) (0,1)
786-- $ Stream.fromList [1,2,3,4]
792-- IMPORTANT: 'scanl'' evaluates the accumulator to WHNF. To avoid building
793-- lazy expressions inside the accumulator, it is recommended that a strict
794-- data structure is used for accumulator.
796-- >>> scanl' f z xs = scanlM' (\a b -> return (f a b)) (return z) xs
797-- >>> scanl' f z xs = z `Stream.cons` postscanl' f z xs
799-- See also: 'usingStateT'
803scanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
804scanl' step z m = fromStreamS $ S.scanl' step z $ toStreamS m
806-- | Like 'scanl'' but does not stream the initial value of the accumulator.
808-- >>> postscanl' f z = postscanlM' (\a b -> return (f a b)) (return z)
809-- >>> postscanl' f z xs = Stream.drop 1 $ Stream.scanl' f z xs
812{-# INLINE postscanl' #-}
813postscanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
814postscanl' step z m = fromStreamD $ D.postscanl' step z $ toStreamD m
816-- XXX prescanl does not sound very useful, enable only if there is a
817-- compelling use case.
819-- | Like scanl' but does not stream the final value of the accumulator.
822{-# INLINE prescanl' #-}
823prescanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
824prescanl' step z m = fromStreamD $ D.prescanl' step z $ toStreamD m
826-- XXX this needs to be concurrent
827-- | Like prescanl' but with a monadic step function and a monadic seed.
830{-# INLINE prescanlM' #-}
831prescanlM' :: (IsStream t, Monad m) => (b -> a -> m b) -> m b -> t m a -> t m b
832prescanlM' step z m = fromStreamD $ D.prescanlM' step z $ toStreamD m
834-- XXX this needs to be concurrent
835-- | Like 'scanl1'' but with a monadic step function.
838{-# INLINE scanl1M' #-}
839scanl1M' :: (IsStream t, Monad m) => (a -> a -> m a) -> t m a -> t m a
840scanl1M' step m = fromStreamD $ D.scanl1M' step $ toStreamD m
842-- | Like 'scanl'' but for a non-empty stream. The first element of the stream
843-- is used as the initial value of the accumulator. Does nothing if the stream
847-- >>> Stream.toList $ Stream.scanl1' (+) $ fromList [1,2,3,4]
853{-# INLINE scanl1' #-}
854scanl1' :: (IsStream t, Monad m) => (a -> a -> a) -> t m a -> t m a
855scanl1' step m = fromStreamD $ D.scanl1' step $ toStreamD m
857------------------------------------------------------------------------------
859------------------------------------------------------------------------------
861-- | Modify a @t m a -> t m a@ stream transformation that accepts a predicate
862-- @(a -> b)@ to accept @((s, a) -> b)@ instead, provided a transformation @t m
863-- a -> t m (s, a)@. Convenient to filter with index or time.
866-- filterWithIndex = with indexed filter
867-- filterWithAbsTime = with timestamped filter
868-- filterWithRelTime = with timeIndexed filter
873with :: forall (t :: (Type -> Type) -> Type -> Type) m a b s. Functor (t m) =>
874 (t m a -> t m (s, a))
875 -> (((s, a) -> b) -> t m (s, a) -> t m (s, a))
876 -> (((s, a) -> b) -> t m a -> t m a)
877with f comb g = fmap snd . comb g . f
879-- | Include only those elements that pass a predicate.
883filter :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m a
884filter p m = fromStreamS $ S.filter p $ toStreamS m
886-- | Same as 'filter' but with a monadic predicate.
889{-# INLINE filterM #-}
890filterM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
891filterM p m = fromStreamD $ D.filterM p $ toStreamD m
893-- | Drop repeated elements that are adjacent to each other using the supplied
894-- comparison function.
896-- @uniq = uniqBy (==)
898-- To strip duplicate path separators:
901-- f x y = x == '/' && x == y
902-- Stream.toList $ Stream.uniqBy f $ Stream.fromList "//a//b"
913uniqBy :: (IsStream t, Monad m, Functor (t m)) =>
914 (a -> a -> Bool) -> t m a -> t m a
915uniqBy eq = catMaybes . rollingMap f
922 Just x -> if x `eq` curr then Nothing else Just curr
924-- | Drop repeated elements that are adjacent to each other.
928uniq :: (Eq a, IsStream t, Monad m) => t m a -> t m a
929uniq = fromStreamD . D.uniq . toStreamD
931-- | Strip all leading and trailing occurrences of an element passing a
932-- predicate and make all other consecutive occurrences uniq.
935-- prune p = dropWhileAround p $ uniqBy (x y -> p x && p y)
939-- > Stream.prune isSpace (Stream.fromList " hello world! ")
949 -- (IsStream t, Monad m, Eq a) =>
950 (a -> Bool) -> t m a -> t m a
951prune = error "Not implemented yet!"
953-- Possible implementation:
955-- Stream.catMaybes . Stream.parseMany (Parser.groupBy (==) Fold.repeated)@
957-- 'Fold.repeated' should return 'Just' when repeated, and 'Nothing' for a
960-- | Emit only repeated elements, once.
963repeated :: -- (IsStream t, Monad m, Eq a) =>
967-- We can have more efficient implementations for nubOrd and nubInt by using
968-- Set and IntSet to find/remove duplication. For Hashable we can use a
969-- hashmap. Use rewrite rules to specialize to more efficient impls.
971-- | Drop repeated elements anywhere in the stream.
973-- /Caution: not scalable for infinite streams/
975-- /See also: nubWindowBy/
980nubBy :: -- (IsStream t, Monad m) =>
981 (a -> a -> Bool) -> t m a -> t m a
982nubBy = undefined -- fromStreamD . D.nubBy . toStreamD
984-- | Drop repeated elements within the specified tumbling window in the stream.
986-- @nubBy = nubWindowBy maxBound@
990{-# INLINE nubWindowBy #-}
991nubWindowBy :: -- (IsStream t, Monad m) =>
992 Int -> (a -> a -> Bool) -> t m a -> t m a
993nubWindowBy = undefined -- fromStreamD . D.nubWithinBy . toStreamD
995-- | Deletes the first occurrence of the element in the stream that satisfies
996-- the given equality predicate.
999-- >>> Stream.toList $ Stream.deleteBy (==) 3 $ Stream.fromList [1,3,3,5]
1005{-# INLINE deleteBy #-}
1006deleteBy :: (IsStream t, Monad m) => (a -> a -> Bool) -> a -> t m a -> t m a
1007deleteBy cmp x m = fromStreamS $ S.deleteBy cmp x (toStreamS m)
1009------------------------------------------------------------------------------
1011------------------------------------------------------------------------------
1013-- XXX We could use 'maxBuffer Block/Drop/Rotate/Sample' instead. However we
1014-- may want to have the evaluation rate independent of the sampling rate. To
1015-- support that we can decouple evaluation and sampling in independent stages.
1016-- The sampling stage would strictly evaluate and sample, the evaluation stage
1017-- would control the evaluation rate.
1019-- | Evaluate the input stream continuously and keep only the oldest @n@
1020-- elements in the buffer, discard the new ones when the buffer is full. When
1021-- the output stream is evaluated it consumes the values from the buffer in a
1026{-# INLINE sampleOld #-}
1027sampleOld :: -- (IsStream t, Monad m) =>
1028 Int -> t m a -> t m a
1029sampleOld = undefined
1031-- | Evaluate the input stream continuously and keep only the latest @n@
1032-- elements in a ring buffer, keep discarding the older ones to make space for
1033-- the new ones. When the output stream is evaluated it consumes the values
1034-- from the buffer in a FIFO manner.
1038{-# INLINE sampleNew #-}
1039sampleNew :: -- (IsStream t, Monad m) =>
1040 Int -> t m a -> t m a
1041sampleNew = undefined
1043-- | Like 'sampleNew' but samples at uniform intervals to match the consumer
1044-- rate. Note that 'sampleNew' leads to non-uniform sampling depending on the
1049{-# INLINE sampleRate #-}
1050sampleRate :: -- (IsStream t, Monad m) =>
1051 Double -> t m a -> t m a
1052sampleRate = undefined
1054------------------------------------------------------------------------------
1056------------------------------------------------------------------------------
1058-- | Same as 'takeWhile' but with a monadic predicate.
1061{-# INLINE takeWhileM #-}
1062takeWhileM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
1063takeWhileM p m = fromStreamD $ D.takeWhileM p $ toStreamD m
1065-- See the lastN fold for impl hints. Use a Data.Array based ring buffer.
1067-- takeLast n = Stream.concatM . fmap Array.toStream . fold Fold.lastN
1069-- | Take @n@ elements at the end of the stream.
1071-- O(n) space, where n is the number elements taken.
1074{-# INLINE takeLast #-}
1075takeLast :: -- (IsStream t, Monad m) =>
1076 Int -> t m a -> t m a
1077takeLast = undefined -- fromStreamD $ D.takeLast n $ toStreamD m
1079-- | Take time interval @i@ seconds at the end of the stream.
1081-- O(n) space, where n is the number elements taken.
1084{-# INLINE takeLastInterval #-}
1085takeLastInterval :: -- (IsStream t, Monad m) =>
1086 Double -> t m a -> t m a
1087takeLastInterval = undefined -- fromStreamD $ D.takeLast n $ toStreamD m
1089-- | Take all consecutive elements at the end of the stream for which the
1090-- predicate is true.
1092-- O(n) space, where n is the number elements taken.
1095{-# INLINE takeWhileLast #-}
1096takeWhileLast :: -- (IsStream t, Monad m) =>
1097 (a -> Bool) -> t m a -> t m a
1098takeWhileLast = undefined -- fromStreamD $ D.takeWhileLast n $ toStreamD m
1100-- | Like 'takeWhile' and 'takeWhileLast' combined.
1102-- O(n) space, where n is the number elements taken from the end.
1105{-# INLINE takeWhileAround #-}
1106takeWhileAround :: -- (IsStream t, Monad m) =>
1107 (a -> Bool) -> t m a -> t m a
1108takeWhileAround = undefined -- fromStreamD $ D.takeWhileAround n $ toStreamD m
1110-- | @takeInterval duration@ yields stream elements upto specified time
1111-- @duration@. The duration starts when the stream is evaluated for the first
1112-- time, before the first element is yielded. The time duration is checked
1113-- before generating each element, if the duration has expired the stream
1116-- The total time taken in executing the stream is guaranteed to be /at least/
1117-- @duration@, however, because the duration is checked before generating an
1118-- element, the upper bound is indeterminate and depends on the time taken in
1119-- generating and processing the last element.
1121-- No element is yielded if the duration is zero. At least one element is
1122-- yielded if the duration is non-zero.
1126{-# INLINE takeInterval #-}
1127takeInterval ::(MonadIO m, IsStream t, TimeUnit64 d) => d -> t m a -> t m a
1128takeInterval d = fromStreamD . D.takeByTime d . toStreamD
1130-- | Drop elements in the stream as long as the predicate succeeds and then
1131-- take the rest of the stream.
1134{-# INLINE dropWhile #-}
1135dropWhile :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m a
1136dropWhile p m = fromStreamS $ S.dropWhile p $ toStreamS m
1138-- | Same as 'dropWhile' but with a monadic predicate.
1141{-# INLINE dropWhileM #-}
1142dropWhileM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
1143dropWhileM p m = fromStreamD $ D.dropWhileM p $ toStreamD m
1145-- | @dropInterval duration@ drops stream elements until specified @duration@ has
1146-- passed. The duration begins when the stream is evaluated for the first
1147-- time. The time duration is checked /after/ generating a stream element, the
1148-- element is yielded if the duration has expired otherwise it is dropped.
1150-- The time elapsed before starting to generate the first element is /at most/
1151-- @duration@, however, because the duration expiry is checked after the
1152-- element is generated, the lower bound is indeterminate and depends on the
1153-- time taken in generating an element.
1155-- All elements are yielded if the duration is zero.
1159{-# INLINE dropInterval #-}
1160dropInterval ::(MonadIO m, IsStream t, TimeUnit64 d) => d -> t m a -> t m a
1161dropInterval d = fromStreamD . D.dropByTime d . toStreamD
1163-- | Drop @n@ elements at the end of the stream.
1165-- O(n) space, where n is the number elements dropped.
1168{-# INLINE dropLast #-}
1169dropLast :: -- (IsStream t, Monad m) =>
1170 Int -> t m a -> t m a
1171dropLast = undefined -- fromStreamD $ D.dropLast n $ toStreamD m
1173-- | Drop time interval @i@ seconds at the end of the stream.
1175-- O(n) space, where n is the number elements dropped.
1178{-# INLINE dropLastInterval #-}
1179dropLastInterval :: -- (IsStream t, Monad m) =>
1180 Int -> t m a -> t m a
1181dropLastInterval = undefined
1183-- | Drop all consecutive elements at the end of the stream for which the
1184-- predicate is true.
1186-- O(n) space, where n is the number elements dropped.
1189{-# INLINE dropWhileLast #-}
1190dropWhileLast :: -- (IsStream t, Monad m) =>
1191 (a -> Bool) -> t m a -> t m a
1192dropWhileLast = undefined -- fromStreamD $ D.dropWhileLast n $ toStreamD m
1194-- | Like 'dropWhile' and 'dropWhileLast' combined.
1196-- O(n) space, where n is the number elements dropped from the end.
1199{-# INLINE dropWhileAround #-}
1200dropWhileAround :: -- (IsStream t, Monad m) =>
1201 (a -> Bool) -> t m a -> t m a
1202dropWhileAround = undefined -- fromStreamD $ D.dropWhileAround n $ toStreamD m
1204------------------------------------------------------------------------------
1205-- Inserting Elements
1206------------------------------------------------------------------------------
1208-- | @insertBy cmp elem stream@ inserts @elem@ before the first element in
1209-- @stream@ that is less than @elem@ when compared using @cmp@.
1212-- insertBy cmp x = 'mergeBy' cmp ('fromPure' x)
1216-- >>> Stream.toList $ Stream.insertBy compare 2 $ Stream.fromList [1,3,5]
1222{-# INLINE insertBy #-}
1224 (IsStream t, Monad m) => (a -> a -> Ordering) -> a -> t m a -> t m a
1225insertBy cmp x m = fromStreamS $ S.insertBy cmp x (toStreamS m)
1227-- | Insert a pure value between successive elements of a stream.
1229-- >>> Stream.toList $ Stream.intersperse ',' $ Stream.fromList "hello"
1233{-# INLINE intersperse #-}
1234intersperse :: (IsStream t, MonadAsync m) => a -> t m a -> t m a
1235intersperse a = fromStreamS . S.intersperse a . toStreamS
1237-- | Insert a side effect before consuming an element of a stream except the
1240-- >>> Stream.drain $ Stream.trace putChar $ Stream.intersperseM_ (putChar '.') $ Stream.fromList "hello"
1244{-# INLINE intersperseM_ #-}
1245intersperseM_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
1246intersperseM_ m = fromStreamD . D.intersperseM_ m . toStreamD
1248-- | Intersperse a monadic action into the input stream after every @n@
1252-- > Stream.toList $ Stream.intersperseBySpan 2 (return ',') $ Stream.fromList "hello"
1258{-# INLINE intersperseBySpan #-}
1259intersperseBySpan :: -- IsStream t =>
1260 Int -> m a -> t m a -> t m a
1261intersperseBySpan _n _f _xs = undefined
1263-- | Insert an effect and its output after consuming an element of a stream.
1265-- >>> Stream.toList $ Stream.trace putChar $ intersperseSuffix (putChar '.' >> return ',') $ Stream.fromList "hello"
1266-- h.,e.,l.,l.,o.,"h,e,l,l,o,"
1269{-# INLINE intersperseSuffix #-}
1270intersperseSuffix :: (IsStream t, Monad m) => m a -> t m a -> t m a
1271intersperseSuffix m = fromStreamD . D.intersperseSuffix m . toStreamD
1273-- | Insert a side effect after consuming an element of a stream.
1276-- >>> Stream.mapM_ putChar $ Stream.intersperseSuffix_ (threadDelay 1000000) $ Stream.fromList "hello"
1283{-# INLINE intersperseSuffix_ #-}
1284intersperseSuffix_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
1285intersperseSuffix_ m = fromStreamD . D.intersperseSuffix_ m . toStreamD
1287-- XXX Use an offset argument, like tapOffsetEvery
1289-- | Like 'intersperseSuffix' but intersperses an effectful action into the
1290-- input stream after every @n@ elements and after the last element.
1292-- >>> Stream.toList $ Stream.intersperseSuffixBySpan 2 (return ',') $ Stream.fromList "hello"
1297{-# INLINE intersperseSuffixBySpan #-}
1298intersperseSuffixBySpan :: (IsStream t, Monad m)
1299 => Int -> m a -> t m a -> t m a
1300intersperseSuffixBySpan n eff =
1301 fromStreamD . D.intersperseSuffixBySpan n eff . toStreamD
1303-- | Insert a side effect before consuming an element of a stream.
1305-- >>> Stream.toList $ Stream.trace putChar $ Stream.interspersePrefix_ (putChar '.' >> return ',') $ Stream.fromList "hello"
1308-- Same as 'trace_' but may be concurrent.
1314{-# INLINE interspersePrefix_ #-}
1315interspersePrefix_ :: (IsStream t, MonadAsync m) => m b -> t m a -> t m a
1316interspersePrefix_ m = mapM (\x -> void m >> return x)
1318------------------------------------------------------------------------------
1320------------------------------------------------------------------------------
1322-- Note: delay must be serial.
1324-- | Introduce a delay of specified seconds before consuming an element of the
1325-- stream except the first one.
1327-- >>> Stream.mapM_ print $ Stream.timestamped $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
1328-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),1)
1329-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),2)
1330-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),3)
1335delay :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
1336delay n = intersperseM_ $ liftIO $ threadDelay $ round $ n * 1000000
1338-- Note: delay must be serial.
1340-- | Introduce a delay of specified seconds after consuming an element of a
1343-- >>> Stream.mapM_ print $ Stream.timestamped $ Stream.delayPost 1 $ Stream.enumerateFromTo 1 3
1344-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),1)
1345-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),2)
1346-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),3)
1350{-# INLINE delayPost #-}
1351delayPost :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
1352delayPost n = intersperseSuffix_ $ liftIO $ threadDelay $ round $ n * 1000000
1354-- Note: delay must be serial, that's why 'trace_' is used.
1356-- | Introduce a delay of specified seconds before consuming an element of a
1359-- >>> Stream.mapM_ print $ Stream.timestamped $ Stream.delayPre 1 $ Stream.enumerateFromTo 1 3
1360-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),1)
1361-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),2)
1362-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),3)
1366{-# INLINE delayPre #-}
1367delayPre :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
1368delayPre n = trace_ $ liftIO $ threadDelay $ round $ n * 1000000
1370------------------------------------------------------------------------------
1371-- Reorder in sequence
1372------------------------------------------------------------------------------
1374-- | Buffer until the next element in sequence arrives. The function argument
1375-- determines the difference in sequence numbers. This could be useful in
1376-- implementing sequenced streams, for example, TCP reassembly.
1380{-# INLINE reassembleBy #-}
1382 :: -- (IsStream t, Monad m) =>
1387reassembleBy = undefined
1389------------------------------------------------------------------------------
1391------------------------------------------------------------------------------
1394-- > indexed = Stream.postscanl' (\(i, _) x -> (i + 1, x)) (-1,undefined)
1395-- > indexed = Stream.zipWith (,) (Stream.enumerateFrom 0)
1397-- Pair each element in a stream with its index, starting from index 0.
1399-- >>> Stream.toList $ Stream.indexed $ Stream.fromList "hello"
1400-- [(0,'h'),(1,'e'),(2,'l'),(3,'l'),(4,'o')]
1403{-# INLINE indexed #-}
1404indexed :: (IsStream t, Monad m) => t m a -> t m (Int, a)
1405indexed = fromStreamD . D.indexed . toStreamD
1408-- > indexedR n = Stream.postscanl' (\(i, _) x -> (i - 1, x)) (n + 1,undefined)
1409-- > indexedR n = Stream.zipWith (,) (Stream.enumerateFromThen n (n - 1))
1411-- Pair each element in a stream with its index, starting from the
1412-- given index @n@ and counting down.
1414-- >>> Stream.toList $ Stream.indexedR 10 $ Stream.fromList "hello"
1415-- [(10,'h'),(9,'e'),(8,'l'),(7,'l'),(6,'o')]
1418{-# INLINE indexedR #-}
1419indexedR :: (IsStream t, Monad m) => Int -> t m a -> t m (Int, a)
1420indexedR n = fromStreamD . D.indexedR n . toStreamD
1422-------------------------------------------------------------------------------
1424-------------------------------------------------------------------------------
1426-- Note: The timestamp stream must be the second stream in the zip so that the
1427-- timestamp is generated after generating the stream element and not before.
1428-- If we do not do that then the following example will generate the same
1429-- timestamp for first two elements:
1431-- Stream.mapM_ print $ Stream.timestamped $ Stream.delay $ Stream.enumerateFromTo 1 3
1433-- | Pair each element in a stream with an absolute timestamp, using a clock of
1434-- specified granularity. The timestamp is generated just before the element
1437-- >>> Stream.mapM_ print $ Stream.timestampWith 0.01 $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
1438-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),1)
1439-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),2)
1440-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),3)
1444{-# INLINE timestampWith #-}
1445timestampWith :: (IsStream t, MonadAsync m, Functor (t m))
1446 => Double -> t m a -> t m (AbsTime, a)
1447timestampWith g stream = zipWith (flip (,)) stream (absTimesWith g)
1449-- TBD: check performance vs a custom implementation without using zipWith.
1453{-# INLINE timestamped #-}
1454timestamped :: (IsStream t, MonadAsync m, Functor (t m))
1455 => t m a -> t m (AbsTime, a)
1456timestamped = timestampWith 0.01
1458-- | Pair each element in a stream with relative times starting from 0, using a
1459-- clock with the specified granularity. The time is measured just before the
1460-- element is consumed.
1462-- >>> Stream.mapM_ print $ Stream.timeIndexWith 0.01 $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
1463-- (RelTime64 (NanoSecond64 ...),1)
1464-- (RelTime64 (NanoSecond64 ...),2)
1465-- (RelTime64 (NanoSecond64 ...),3)
1469{-# INLINE timeIndexWith #-}
1470timeIndexWith :: (IsStream t, MonadAsync m, Functor (t m))
1471 => Double -> t m a -> t m (RelTime64, a)
1472timeIndexWith g stream = zipWith (flip (,)) stream (relTimesWith g)
1474-- | Pair each element in a stream with relative times starting from 0, using a
1475-- 10 ms granularity clock. The time is measured just before the element is
1478-- >>> Stream.mapM_ print $ Stream.timeIndexed $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
1479-- (RelTime64 (NanoSecond64 ...),1)
1480-- (RelTime64 (NanoSecond64 ...),2)
1481-- (RelTime64 (NanoSecond64 ...),3)
1485{-# INLINE timeIndexed #-}
1486timeIndexed :: (IsStream t, MonadAsync m, Functor (t m))
1487 => t m a -> t m (RelTime64, a)
1488timeIndexed = timeIndexWith 0.01
1490------------------------------------------------------------------------------
1492------------------------------------------------------------------------------
1494-- | Find all the indices where the value of the element in the stream is equal
1495-- to the given value.
1497-- > elemIndices a = findIndices (== a)
1500{-# INLINE elemIndices #-}
1501elemIndices :: (IsStream t, Eq a, Monad m) => a -> t m a -> t m Int
1502elemIndices a = findIndices (== a)
1504------------------------------------------------------------------------------
1506------------------------------------------------------------------------------
1508-- XXX this is not a one-to-one map so calling it map may not be right.
1509-- We can perhaps call it zipWithTail or rollWith.
1511-- | Apply a function on every two successive elements of a stream. The first
1512-- argument of the map function is the previous element and the second argument
1513-- is the current element. When the current element is the first element, the
1514-- previous element is 'Nothing'.
1518{-# INLINE rollingMap #-}
1519rollingMap :: (IsStream t, Monad m) => (Maybe a -> a -> b) -> t m a -> t m b
1520rollingMap f m = fromStreamD $ D.rollingMap f $ toStreamD m
1522-- | Like 'rollingMap' but with an effectful map function.
1526{-# INLINE rollingMapM #-}
1527rollingMapM :: (IsStream t, Monad m) => (Maybe a -> a -> m b) -> t m a -> t m b
1528rollingMapM f m = fromStreamD $ D.rollingMapM f $ toStreamD m
1530-- | Like 'rollingMap' but requires at least two elements in the stream,
1531-- returns an empty stream otherwise.
1533-- This is the stream equivalent of the list idiom @zipWith f xs (tail xs)@.
1537{-# INLINE rollingMap2 #-}
1538rollingMap2 :: (IsStream t, Monad m) => (a -> a -> b) -> t m a -> t m b
1539rollingMap2 f m = fromStreamD $ D.rollingMap2 f $ toStreamD m
1541------------------------------------------------------------------------------
1543------------------------------------------------------------------------------
1545-- | Map a 'Maybe' returning function to a stream, filter out the 'Nothing'
1546-- elements, and return a stream of values extracted from 'Just'.
1551-- mapMaybe f = Stream.map 'fromJust' . Stream.filter 'isJust' . Stream.map f
1555{-# INLINE mapMaybe #-}
1556mapMaybe :: (IsStream t, Monad m) => (a -> Maybe b) -> t m a -> t m b
1557mapMaybe f m = fromStreamS $ S.mapMaybe f $ toStreamS m
1559-- | Like 'mapMaybe' but maps a monadic function.
1564-- mapMaybeM f = Stream.map 'fromJust' . Stream.filter 'isJust' . Stream.mapM f
1567-- /Concurrent (do not use with 'fromParallel' on infinite streams)/
1570{-# INLINE_EARLY mapMaybeM #-}
1571mapMaybeM :: (IsStream t, MonadAsync m, Functor (t m))
1572 => (a -> m (Maybe b)) -> t m a -> t m b
1573mapMaybeM f = fmap fromJust . filter isJust . mapM f
1575{-# RULES "mapMaybeM serial" mapMaybeM = mapMaybeMSerial #-}
1576{-# INLINE mapMaybeMSerial #-}
1577mapMaybeMSerial :: Monad m => (a -> m (Maybe b)) -> SerialT m a -> SerialT m b
1578mapMaybeMSerial f m = fromStreamD $ D.mapMaybeM f $ toStreamD m
1580-- | In a stream of 'Maybe's, discard 'Nothing's and unwrap 'Just's.
1584{-# INLINE catMaybes #-}
1585catMaybes :: (IsStream t, Monad m, Functor (t m)) => t m (Maybe a) -> t m a
1586catMaybes = fmap fromJust . filter isJust
1588------------------------------------------------------------------------------
1590------------------------------------------------------------------------------
1592-- | Discard 'Right's and unwrap 'Left's in an 'Either' stream.
1597lefts :: (IsStream t, Monad m, Functor (t m)) => t m (Either a b) -> t m a
1598lefts = fmap (fromLeft undefined) . filter isLeft
1600-- | Discard 'Left's and unwrap 'Right's in an 'Either' stream.
1604{-# INLINE rights #-}
1605rights :: (IsStream t, Monad m, Functor (t m)) => t m (Either a b) -> t m b
1606rights = fmap (fromRight undefined) . filter isRight
1608-- | Remove the either wrapper and flatten both lefts and as well as rights in
1609-- the output stream.
1614both :: Functor (t m) => t m (Either a a) -> t m a
1615both = fmap (either id id)
1617------------------------------------------------------------------------------
1618-- Concurrent Application
1619------------------------------------------------------------------------------
1621-- | Parallel transform application operator; applies a stream transformation
1622-- function @t m a -> t m b@ to a stream @t m a@ concurrently; the input stream
1623-- is evaluated asynchronously in an independent thread yielding elements to a
1624-- buffer and the transformation function runs in another thread consuming the
1625-- input from the buffer. '|$' is just like regular function application
1626-- operator '$' except that it is concurrent.
1628-- If you read the signature as @(t m a -> t m b) -> (t m a -> t m b)@ you can
1629-- look at it as a transformation that converts a transform function to a
1630-- buffered concurrent transform function.
1632-- The following code prints a value every second even though each stage adds a
1638-- Stream.mapM (\x -> threadDelay 1000000 >> print x)
1639-- |$ Stream.replicateM 3 (threadDelay 1000000 >> return 1)
1647-- /Since: 0.3.0 ("Streamly")/
1651(|$) :: (IsStream t, MonadAsync m) => (t m a -> t m b) -> (t m a -> t m b)
1652-- (|$) f = f . mkAsync
1653(|$) f = f . mkParallel
1661{-# INLINE applyAsync #-}
1662applyAsync :: (IsStream t, MonadAsync m)
1663 => (t m a -> t m b) -> (t m a -> t m b)
1666-- | Same as '|$' but with arguments reversed.
1672-- /Since: 0.3.0 ("Streamly")/
1676(|&) :: (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