2-- Module : Streamly.Internal.Data.Stream.IsStream.Transform
3-- Copyright : (c) 2017 Composewell Technologies
4-- License : BSD-3-Clause
5-- Maintainer : streamly@composewell.com
6-- Stability : experimental
9module Streamly.Internal.Data.Stream.IsStream.Transform
12 -- | Pass through a 'Pipe'.
20 -- | Stateless one-to-one maps.
26 -- * Mapping Side Effects (Observation)
27 -- | See also the intersperse*_ combinators.
36 -- * Scanning By 'Fold'
41 -- | Left scans. Stateful, mostly one-to-one maps.
52 -- XXX Once we have pipes the contravariant transformations can be
53 -- represented by attaching pipes before a transformation.
66 -- | Produce a subset of the stream using criteria based on the values of
67 -- the elements. We can use a concatMap and scan for filtering but these
68 -- combinators are more efficient and convenient.
82 -- | Produce a subset of the stream trimmed at ends.
85 , takeByTime -- takeInterval
93 , dropByTime -- dropInterval
101 -- * Inserting Elements
102 -- | Produce a superset of the stream. This is the opposite of
103 -- filtering/sampling. We can always use concatMap and scan for inserting
104 -- but these combinators are more efficient and convenient.
106 -- Element agnostic (Opposite of sampling)
108 , intersperseM -- XXX naming
112 , intersperseSuffixBySpan
115 -- , interspersePrefix
116 -- , interspersePrefixBySpan
118 -- * Inserting Side Effects/Time
119 , intersperseM_ -- XXX naming
126 -- * Element Aware Insertion
127 -- | Opposite of filtering
129 -- , intersperseByBefore
130 -- , intersperseByAfter
137 -- * Position Indexing
144 -- , timestampedR -- timer
149 , findIndices -- XXX indicesBy
150 , elemIndices -- XXX indicesOf
153 -- | Map using the previous element.
158 -- Move these to Streamly.Data.Maybe.Stream?
159 , catMaybes -- XXX justs (like lefts/rights)
164 -- Move these to Streamly.Data.Either.Stream?
168 -- * Concurrent Evaluation
169 -- ** Concurrent Pipelines
170 -- | Run streaming stages concurrently.
177 -- ** Concurrency Control
180 -- ** Buffering and Sampling
181 -- | Evaluate strictly using a buffer of results. When the buffer becomes
182 -- full we can block, drop the new elements, drop the oldest element and
183 -- insert the new at the end or keep dropping elements uniformly to match
184 -- the rate of the consumer.
191 -- | Evaluate the stream at uniform intervals to maintain a specified
210import Control.Concurrent (threadDelay)
211import Control.Monad (void)
212import Control.Monad.Catch (MonadCatch)
213import Control.Monad.IO.Class (MonadIO(..))
214import Control.Monad.Trans.Class (MonadTrans(..))
215import Data.Either (isLeft, isRight)
216import Data.Kind (Type)
217import Data.Maybe (isJust, fromJust)
218import Streamly.Internal.BaseCompat (fromLeft, fromRight)
219import Streamly.Internal.Data.Fold.Types (Fold (..))
220import Streamly.Internal.Data.Pipe.Types (Pipe (..))
221import Streamly.Internal.Data.Stream.IsStream.Combinators
222 ( inspectMode, maxBuffer, maxThreads, rate, avgRate, minRate
223 , maxRate, constRate)
224import Streamly.Internal.Data.Stream.IsStream.Common
239import Streamly.Internal.Data.Stream.Prelude (fromStreamS, toStreamS)
240import Streamly.Internal.Data.Stream.Serial (SerialT)
241import Streamly.Internal.Data.Stream.StreamD (fromStreamD, toStreamD)
242import Streamly.Internal.Data.Stream.StreamK (IsStream)
243import Streamly.Internal.Data.SVar (MonadAsync, Rate(..))
244import Streamly.Internal.Data.Time.Units (TimeUnit64, AbsTime, RelTime64)
246import qualified Streamly.Internal.Data.Fold as FL
247import qualified Streamly.Internal.Data.Stream.Parallel as Par
248import qualified Streamly.Internal.Data.Stream.Prelude as P
249import qualified Streamly.Internal.Data.Stream.Serial as Serial
250import qualified Streamly.Internal.Data.Stream.StreamD as D
251import qualified Streamly.Internal.Data.Stream.StreamK as K
252import qualified Streamly.Internal.Data.Stream.Zip as Z
253#ifdef USE_STREAMK_ONLY
254import qualified Streamly.Internal.Data.Stream.StreamK as S
256import qualified Streamly.Internal.Data.Stream.StreamD as S
260 ( filter, drop, dropWhile, take, takeWhile, foldr, map, mapM, sequence
261 , reverse, foldr1 , scanl, scanl1)
263------------------------------------------------------------------------------
265------------------------------------------------------------------------------
267-- | Use a 'Pipe' to transform a stream.
271{-# INLINE transform #-}
272transform :: (IsStream t, Monad m) => Pipe m a b -> t m a -> t m b
273transform pipe xs = fromStreamD $ D.transform pipe (toStreamD xs)
275------------------------------------------------------------------------------
276-- Transformation Folds
277------------------------------------------------------------------------------
279-- | Right fold to a streaming monad.
281-- > foldrS S.cons S.nil === id
283-- 'foldrS' can be used to perform stateless stream to stream transformations
284-- like map and filter in general. It can be coupled with a scan to perform
285-- stateful transformations. However, note that the custom map and filter
286-- routines can be much more efficient than this due to better stream fusion.
288-- >>> S.toList $ S.foldrS S.cons S.nil $ S.fromList [1..5]
291-- Find if any element in the stream is 'True':
293-- >>> S.toList $ S.foldrS (\x xs -> if odd x then return True else xs) (return False) $ (S.fromList (2:4:5:undefined) :: SerialT IO Int)
296-- Map (+2) on odd elements and filter out the even elements:
298-- >>> S.toList $ S.foldrS (\x xs -> if odd x then (x + 2) `S.cons` xs else xs) S.nil $ (S.fromList [1..5] :: SerialT IO Int)
301-- 'foldrM' can also be represented in terms of 'foldrS', however, the former
302-- is much more efficient:
304-- > foldrM f z s = runIdentityT $ foldrS (\x xs -> lift $ f x (runIdentityT xs)) (lift z) s
308foldrS :: IsStream t => (a -> t m b -> t m b) -> t m b -> t m a -> t m b
311-- | Right fold to a transformer monad. This is the most general right fold
312-- function. 'foldrS' is a special case of 'foldrT', however 'foldrS'
313-- implementation can be more efficient:
316-- > foldrM f z s = runIdentityT $ foldrT (\x xs -> lift $ f x (runIdentityT xs)) (lift z) s
318-- 'foldrT' can be used to translate streamly streams to other transformer
319-- monads e.g. to a different streaming type.
323foldrT :: (IsStream t, Monad m, Monad (s m), MonadTrans s)
324 => (a -> s m b -> s m b) -> s m b -> t m a -> s m b
325foldrT f z s = S.foldrT f z (toStreamS s)
327------------------------------------------------------------------------------
328-- Transformation by Mapping
329------------------------------------------------------------------------------
333-- mapM f = sequence . map f
336-- Apply a monadic function to each element of the stream and replace it with
337-- the output of the resulting action.
340-- > drain $ S.mapM putStr $ S.fromList ["a", "b", "c"]
343-- drain $ S.replicateM 10 (return 1)
344-- & (serially . S.mapM (\\x -> threadDelay 1000000 >> print x))
346-- drain $ S.replicateM 10 (return 1)
347-- & (asyncly . S.mapM (\\x -> threadDelay 1000000 >> print x))
350-- /Concurrent (do not use with 'parallely' on infinite streams)/
353{-# INLINE_EARLY mapM #-}
354mapM :: (IsStream t, MonadAsync m) => (a -> m b) -> t m a -> t m b
357{-# RULES "mapM serial" mapM = mapMSerial #-}
358{-# INLINE mapMSerial #-}
359mapMSerial :: Monad m => (a -> m b) -> SerialT m a -> SerialT m b
360mapMSerial = Serial.mapM
367-- Replace the elements of a stream of monadic actions with the outputs of
371-- > drain $ S.sequence $ S.fromList [putStr "a", putStr "b", putStrLn "c"]
374-- drain $ S.replicateM 10 (return $ threadDelay 1000000 >> print 1)
375-- & (serially . S.sequence)
377-- drain $ S.replicateM 10 (return $ threadDelay 1000000 >> print 1)
378-- & (asyncly . S.sequence)
381-- /Concurrent (do not use with 'parallely' on infinite streams)/
384{-# INLINE sequence #-}
385sequence :: (IsStream t, MonadAsync m) => t m (m a) -> t m a
386sequence m = fromStreamS $ S.sequence (toStreamS m)
388------------------------------------------------------------------------------
389-- Mapping side effects
390------------------------------------------------------------------------------
392-- | Tap the data flowing through a stream into a 'Fold'. For example, you may
393-- add a tap to log the contents flowing through the stream. The fold is used
394-- only for effects, its result is discarded.
399-- -----stream m a ---------------stream m a-----
404-- > S.drain $ S.tap (FL.drainBy print) (S.enumerateFromTo 1 2)
409-- Compare with 'trace'.
413tap :: (IsStream t, Monad m) => FL.Fold m a b -> t m a -> t m a
414tap f xs = D.fromStreamD $ D.tap f (D.toStreamD xs)
416-- XXX Remove this. It can be expressed in terms of Fold.sampleFromThen.
418-- | @tapOffsetEvery offset n@ taps every @n@th element in the stream
419-- starting at @offset@. @offset@ can be between @0@ and @n - 1@. Offset 0
420-- means start at the first element in the stream. If the offset is outside
421-- this range then @offset `mod` n@ is used as offset.
424-- >>> S.drain $ S.tapOffsetEvery 0 2 (FL.rmapM print FL.toList) $ S.enumerateFromTo 0 10
430{-# INLINE tapOffsetEvery #-}
431tapOffsetEvery :: (IsStream t, Monad m)
432 => Int -> Int -> FL.Fold m a b -> t m a -> t m a
433tapOffsetEvery offset n f xs =
434 D.fromStreamD $ D.tapOffsetEvery offset n f (D.toStreamD xs)
436-- | Redirect a copy of the stream to a supplied fold and run it concurrently
437-- in an independent thread. The fold may buffer some elements. The buffer size
438-- is determined by the prevailing 'maxBuffer' setting.
443-- -----stream m a ---------------stream m a-----
448-- > S.drain $ S.tapAsync (S.mapM_ print) (S.enumerateFromTo 1 2)
453-- Exceptions from the concurrently running fold are propagated to the current
454-- computation. Note that, because of buffering in the fold, exceptions may be
455-- delayed and may not correspond to the current element being processed in the
456-- parent stream, but we guarantee that before the parent stream stops the tap
457-- finishes and all exceptions from it are drained.
460-- Compare with 'tap'.
463{-# INLINE tapAsync #-}
464tapAsync :: (IsStream t, MonadAsync m) => FL.Fold m a b -> t m a -> t m a
465tapAsync f xs = D.fromStreamD $ Par.tapAsyncF f (D.toStreamD xs)
467-- | @pollCounts predicate transform fold stream@ counts those elements in the
468-- stream that pass the @predicate@. The resulting count stream is sent to
469-- another thread which transforms it using @transform@ and then folds it using
470-- @fold@. The thread is automatically cleaned up if the stream stops or
471-- aborts due to exception.
473-- For example, to print the count of elements processed every second:
476-- > S.drain $ S.pollCounts (const True) (S.rollingMap (-) . S.delayPost 1) (FL.drainBy print)
477-- $ S.enumerateFrom 0
480-- Note: This may not work correctly on 32-bit machines.
484{-# INLINE pollCounts #-}
486 (IsStream t, MonadAsync m)
488 -> (t m Int -> t m Int)
492pollCounts predicate transf f xs =
494 $ D.pollCounts predicate (D.toStreamD . transf . D.fromStreamD) f
497-- | Calls the supplied function with the number of elements consumed
498-- every @n@ seconds. The given function is run in a separate thread
499-- until the end of the stream. In case there is an exception in the
500-- stream the thread is killed during the next major GC.
502-- Note: The action is not guaranteed to run if the main thread exits.
505-- > delay n = threadDelay (round $ n * 1000000) >> return n
506-- > S.drain $ S.tapRate 2 (\\n -> print $ show n ++ " elements processed") (delay 1 S.|: delay 0.5 S.|: delay 0.5 S.|: S.nil)
507-- 2 elements processed
508-- 1 elements processed
511-- Note: This may not work correctly on 32-bit machines.
514{-# INLINE tapRate #-}
516 (IsStream t, MonadAsync m, MonadCatch m)
521tapRate n f xs = D.fromStreamD $ D.tapRate n f $ D.toStreamD xs
523-- | Apply a monadic function to each element flowing through the stream and
524-- discard the results.
527-- > S.drain $ S.trace print (S.enumerateFromTo 1 2)
532-- Compare with 'tap'.
536trace :: (IsStream t, MonadAsync m) => (a -> m b) -> t m a -> t m a
537trace f = mapM (\x -> void (f x) >> return x)
539-- | Perform a side effect before yielding each element of the stream and
540-- discard the results.
543-- > S.drain $ S.trace_ (print "got here") (S.enumerateFromTo 1 2)
548-- Same as 'interspersePrefix_' but always serial.
554trace_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
555trace_ eff = Serial.mapM (\x -> eff >> return x)
557------------------------------------------------------------------------------
558-- Scanning with a Fold
559------------------------------------------------------------------------------
561-- | Scan a stream using the given monadic fold.
565scan :: (IsStream t, Monad m) => Fold m a b -> t m a -> t m b
568-- | Postscan a stream using the given monadic fold.
571{-# INLINE postscan #-}
572postscan :: (IsStream t, Monad m) => Fold m a b -> t m a -> t m b
573postscan = P.postscanOnce
575------------------------------------------------------------------------------
576-- Scanning - Transformation by Folding
577------------------------------------------------------------------------------
579-- XXX It may be useful to have a version of scan where we can keep the
580-- accumulator independent of the value emitted. So that we do not necessarily
581-- have to keep a value in the accumulator which we are not using. We can pass
582-- an extraction function that will take the accumulator and the current value
583-- of the element and emit the next value in the stream. That will also make it
584-- possible to modify the accumulator after using it. In fact, the step function
585-- can return new accumulator and the value to be emitted. The signature would
586-- be more like mapAccumL. Or we can change the signature of scanx to
589-- | Strict left scan with an extraction function. Like 'scanl'', but applies a
590-- user supplied extraction function (the third argument) at each step. This is
591-- designed to work with the @foldl@ library. The suffix @x@ is a mnemonic for
596-- /Since: 0.7.0 (Monad m constraint)/
597{-# DEPRECATED scanx "Please use scanl followed by map instead." #-}
599scanx :: (IsStream t, Monad m) => (x -> a -> x) -> x -> (x -> b) -> t m a -> t m b
602-- XXX this needs to be concurrent
603-- XXX because of the use of D.cons for appending, scanlM' has quadratic
604-- complexity when iterated over a stream. We should use StreamK style scanlM'
605-- for linear performance on iteration.
607-- | Like 'scanl'' but with a monadic step function and a monadic seed.
611-- /Since: 0.8.0 (signature change)/
612{-# INLINE scanlM' #-}
613scanlM' :: (IsStream t, Monad m) => (b -> a -> m b) -> m b -> t m a -> t m b
614scanlM' step begin m = fromStreamD $ D.scanlM' step begin $ toStreamD m
616-- XXX because of the use of D.cons for appending, scanl' has quadratic
617-- complexity when iterated over a stream. We should use StreamK style scanlM'
618-- for linear performance on iteration.
620-- | Strict left scan. Like 'map', 'scanl'' too is a one to one transformation,
621-- however it adds an extra element.
624-- > S.toList $ S.scanl' (+) 0 $ fromList [1,2,3,4]
629-- > S.toList $ S.scanl' (flip (:)) [] $ S.fromList [1,2,3,4]
630-- [[],[1],[2,1],[3,2,1],[4,3,2,1]]
633-- The output of 'scanl'' is the initial value of the accumulator followed by
634-- all the intermediate steps and the final result of 'foldl''.
636-- By streaming the accumulated state after each fold step, we can share the
637-- state across multiple stages of stream composition. Each stage can modify or
638-- extend the state, do some processing with it and emit it for the next stage,
639-- thus modularizing the stream processing. This can be useful in
640-- stateful or event-driven programming.
642-- Consider the following monolithic example, computing the sum and the product
643-- of the elements in a stream in one go using a @foldl'@:
646-- > S.foldl' (\\(s, p) x -> (s + x, p * x)) (0,1) $ S.fromList \[1,2,3,4]
650-- Using @scanl'@ we can make it modular by computing the sum in the first
651-- stage and passing it down to the next stage for computing the product:
654-- > S.foldl' (\\(_, p) (s, x) -> (s, p * x)) (0,1)
655-- $ S.scanl' (\\(s, _) x -> (s + x, x)) (0,1)
656-- $ S.fromList \[1,2,3,4]
660-- IMPORTANT: 'scanl'' evaluates the accumulator to WHNF. To avoid building
661-- lazy expressions inside the accumulator, it is recommended that a strict
662-- data structure is used for accumulator.
664-- See also: 'usingStateT'
668scanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
669scanl' step z m = fromStreamS $ S.scanl' step z $ toStreamS m
671-- | Like 'scanl'' but does not stream the initial value of the accumulator.
673-- > postscanl' f z xs = S.drop 1 $ S.scanl' f z xs
676{-# INLINE postscanl' #-}
677postscanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
678postscanl' step z m = fromStreamD $ D.postscanl' step z $ toStreamD m
680-- XXX prescanl does not sound very useful, enable only if there is a
681-- compelling use case.
683-- | Like scanl' but does not stream the final value of the accumulator.
686{-# INLINE prescanl' #-}
687prescanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
688prescanl' step z m = fromStreamD $ D.prescanl' step z $ toStreamD m
690-- XXX this needs to be concurrent
691-- | Like prescanl' but with a monadic step function and a monadic seed.
694{-# INLINE prescanlM' #-}
695prescanlM' :: (IsStream t, Monad m) => (b -> a -> m b) -> m b -> t m a -> t m b
696prescanlM' step z m = fromStreamD $ D.prescanlM' step z $ toStreamD m
698-- XXX this needs to be concurrent
699-- | Like 'scanl1'' but with a monadic step function.
702{-# INLINE scanl1M' #-}
703scanl1M' :: (IsStream t, Monad m) => (a -> a -> m a) -> t m a -> t m a
704scanl1M' step m = fromStreamD $ D.scanl1M' step $ toStreamD m
706-- | Like 'scanl'' but for a non-empty stream. The first element of the stream
707-- is used as the initial value of the accumulator. Does nothing if the stream
711-- > S.toList $ S.scanl1 (+) $ fromList [1,2,3,4]
716{-# INLINE scanl1' #-}
717scanl1' :: (IsStream t, Monad m) => (a -> a -> a) -> t m a -> t m a
718scanl1' step m = fromStreamD $ D.scanl1' step $ toStreamD m
720------------------------------------------------------------------------------
722------------------------------------------------------------------------------
724-- | Modify a @t m a -> t m a@ stream transformation that accepts a predicate
725-- @(a -> b)@ to accept @((s, a) -> b)@ instead, provided a transformation @t m
726-- a -> t m (s, a)@. Convenient to filter with index or time.
729-- filterWithIndex = with indexed filter
730-- filterWithAbsTime = with timestamped filter
731-- filterWithRelTime = with timeIndexed filter
736with :: forall (t :: (Type -> Type) -> Type -> Type) m a b s. Functor (t m) =>
737 (t m a -> t m (s, a))
738 -> (((s, a) -> b) -> t m (s, a) -> t m (s, a))
739 -> (((s, a) -> b) -> t m a -> t m a)
740with f comb g = fmap snd . comb g . f
742-- | Include only those elements that pass a predicate.
746#if __GLASGOW_HASKELL__ != 802
747-- GHC 8.2.2 crashes with this code, when used with "stack"
748filter :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m a
749filter p m = fromStreamS $ S.filter p $ toStreamS m
751filter :: IsStream t => (a -> Bool) -> t m a -> t m a
755-- | Same as 'filter' but with a monadic predicate.
758{-# INLINE filterM #-}
759filterM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
760filterM p m = fromStreamD $ D.filterM p $ toStreamD m
762-- | Drop repeated elements that are adjacent to each other using the supplied
763-- comparison function.
765-- @uniq = uniqBy (==)
767-- To strip duplicate path separators:
770-- f x y = x == '/' && x == y
771-- Stream.toList $ Stream.uniqBy f $ Stream.fromList "//a//b"
782uniqBy :: (IsStream t, Monad m, Functor (t m)) =>
783 (a -> a -> Bool) -> t m a -> t m a
785 catMaybes . rollingMap (\x y -> if x `eq` y then Nothing else Just y)
787-- | Drop repeated elements that are adjacent to each other.
791uniq :: (Eq a, IsStream t, Monad m) => t m a -> t m a
792uniq = fromStreamD . D.uniq . toStreamD
794-- | Strip all leading and trailing occurrences of an element passing a
795-- predicate and make all other consecutive occurrences uniq.
798-- prune p = dropWhileAround p $ uniqBy (x y -> p x && p y)
801-- >>> Stream.pruneBy isSpace (Stream.fromList " hello world! ")
809 -- (IsStream t, Monad m, Eq a) =>
810 (a -> Bool) -> t m a -> t m a
811prune = error "Not implemented yet!"
813-- Possible implementation:
815-- Stream.catMaybes . Stream.parseMany (Parser.groupBy (==) Fold.repeated)@
817-- 'Fold.repeated' should return 'Just' when repeated, and 'Nothing' for a
820-- | Emit only repeated elements, once.
823repeated :: -- (IsStream t, Monad m, Eq a) =>
827-- We can have more efficient implementations for nubOrd and nubInt by using
828-- Set and IntSet to find/remove duplication. For Hashable we can use a
829-- hashmap. Use rewrite rules to specialize to more efficient impls.
831-- | Drop repeated elements anywhere in the stream.
833-- /Caution: not scalable for infinite streams/
835-- /See also: nubWindowBy/
840nubBy :: -- (IsStream t, Monad m) =>
841 (a -> a -> Bool) -> t m a -> t m a
842nubBy = undefined -- fromStreamD . D.nubBy . toStreamD
844-- | Drop repeated elements within the specified tumbling window in the stream.
846-- @nubBy = nubWindowBy maxBound@
850{-# INLINE nubWindowBy #-}
851nubWindowBy :: -- (IsStream t, Monad m) =>
852 Int -> (a -> a -> Bool) -> t m a -> t m a
853nubWindowBy = undefined -- fromStreamD . D.nubWithinBy . toStreamD
855-- | Deletes the first occurrence of the element in the stream that satisfies
856-- the given equality predicate.
859-- > S.toList $ S.deleteBy (==) 3 $ S.fromList [1,3,3,5]
864{-# INLINE deleteBy #-}
865deleteBy :: (IsStream t, Monad m) => (a -> a -> Bool) -> a -> t m a -> t m a
866deleteBy cmp x m = fromStreamS $ S.deleteBy cmp x (toStreamS m)
868------------------------------------------------------------------------------
870------------------------------------------------------------------------------
872-- XXX We could use 'maxBuffer Block/Drop/Rotate/Sample' instead. However we
873-- may want to have the evaluation rate independent of the sampling rate. To
874-- support that we can decouple evaluation and sampling in independent stages.
875-- The sampling stage would strictly evaluate and sample, the evaluation stage
876-- would control the evaluation rate.
878-- | Evaluate the input stream continuously and keep only the oldest @n@
879-- elements in the buffer, discard the new ones when the buffer is full. When
880-- the output stream is evaluated it consumes the values from the buffer in a
885{-# INLINE sampleOld #-}
886sampleOld :: -- (IsStream t, Monad m) =>
887 Int -> t m a -> t m a
890-- | Evaluate the input stream continuously and keep only the latest @n@
891-- elements in a ring buffer, keep discarding the older ones to make space for
892-- the new ones. When the output stream is evaluated it consumes the values
893-- from the buffer in a FIFO manner.
897{-# INLINE sampleNew #-}
898sampleNew :: -- (IsStream t, Monad m) =>
899 Int -> t m a -> t m a
902-- | Like 'sampleNew' but samples at uniform intervals to match the consumer
903-- rate. Note that 'sampleNew' leads to non-uniform sampling depending on the
908{-# INLINE sampleRate #-}
909sampleRate :: -- (IsStream t, Monad m) =>
910 Double -> t m a -> t m a
911sampleRate = undefined
913------------------------------------------------------------------------------
915------------------------------------------------------------------------------
917-- | Same as 'takeWhile' but with a monadic predicate.
920{-# INLINE takeWhileM #-}
921takeWhileM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
922takeWhileM p m = fromStreamD $ D.takeWhileM p $ toStreamD m
924-- See the lastN fold for impl hints. Use a Data.Array based ring buffer.
926-- takeEnd n = Stream.concatM . fmap Array.toStream . fold Fold.lastN
928-- | Take @n@ elements at the end of the stream.
930-- O(n) space, where n is the number elements taken.
933{-# INLINE takeEnd #-}
934takeEnd :: -- (IsStream t, Monad m) =>
935 Int -> t m a -> t m a
936takeEnd = undefined -- fromStreamD $ D.takeEnd n $ toStreamD m
938-- | Take time interval @i@ seconds at the end of the stream.
940-- O(n) space, where n is the number elements taken.
943{-# INLINE takeEndInterval #-}
944takeEndInterval :: -- (IsStream t, Monad m) =>
945 Double -> t m a -> t m a
946takeEndInterval = undefined -- fromStreamD $ D.takeEnd n $ toStreamD m
948-- | Take all consecutive elements at the end of the stream for which the
951-- O(n) space, where n is the number elements taken.
954{-# INLINE takeWhileEnd #-}
955takeWhileEnd :: -- (IsStream t, Monad m) =>
956 (a -> Bool) -> t m a -> t m a
957takeWhileEnd = undefined -- fromStreamD $ D.takeWhileEnd n $ toStreamD m
959-- | Like 'takeWhile' and 'takeWhileEnd' combined.
961-- O(n) space, where n is the number elements taken from the end.
964{-# INLINE takeWhileAround #-}
965takeWhileAround :: -- (IsStream t, Monad m) =>
966 (a -> Bool) -> t m a -> t m a
967takeWhileAround = undefined -- fromStreamD $ D.takeWhileAround n $ toStreamD m
969-- | @takeByTime duration@ yields stream elements upto specified time
970-- @duration@. The duration starts when the stream is evaluated for the first
971-- time, before the first element is yielded. The time duration is checked
972-- before generating each element, if the duration has expired the stream
975-- The total time taken in executing the stream is guaranteed to be /at least/
976-- @duration@, however, because the duration is checked before generating an
977-- element, the upper bound is indeterminate and depends on the time taken in
978-- generating and processing the last element.
980-- No element is yielded if the duration is zero. At least one element is
981-- yielded if the duration is non-zero.
985{-# INLINE takeByTime #-}
986takeByTime ::(MonadIO m, IsStream t, TimeUnit64 d) => d -> t m a -> t m a
987takeByTime d = fromStreamD . D.takeByTime d . toStreamD
989-- | Drop elements in the stream as long as the predicate succeeds and then
990-- take the rest of the stream.
993{-# INLINE dropWhile #-}
994dropWhile :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m a
995dropWhile p m = fromStreamS $ S.dropWhile p $ toStreamS m
997-- | Same as 'dropWhile' but with a monadic predicate.
1000{-# INLINE dropWhileM #-}
1001dropWhileM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
1002dropWhileM p m = fromStreamD $ D.dropWhileM p $ toStreamD m
1004-- | @dropByTime duration@ drops stream elements until specified @duration@ has
1005-- passed. The duration begins when the stream is evaluated for the first
1006-- time. The time duration is checked /after/ generating a stream element, the
1007-- element is yielded if the duration has expired otherwise it is dropped.
1009-- The time elapsed before starting to generate the first element is /at most/
1010-- @duration@, however, because the duration expiry is checked after the
1011-- element is generated, the lower bound is indeterminate and depends on the
1012-- time taken in generating an element.
1014-- All elements are yielded if the duration is zero.
1018{-# INLINE dropByTime #-}
1019dropByTime ::(MonadIO m, IsStream t, TimeUnit64 d) => d -> t m a -> t m a
1020dropByTime d = fromStreamD . D.dropByTime d . toStreamD
1022-- | Drop @n@ elements at the end of the stream.
1024-- O(n) space, where n is the number elements dropped.
1027{-# INLINE dropEnd #-}
1028dropEnd :: -- (IsStream t, Monad m) =>
1029 Int -> t m a -> t m a
1030dropEnd = undefined -- fromStreamD $ D.dropEnd n $ toStreamD m
1032-- | Drop time interval @i@ seconds at the end of the stream.
1034-- O(n) space, where n is the number elements dropped.
1037{-# INLINE dropEndInterval #-}
1038dropEndInterval :: -- (IsStream t, Monad m) =>
1039 Int -> t m a -> t m a
1040dropEndInterval = undefined
1042-- | Drop all consecutive elements at the end of the stream for which the
1043-- predicate is true.
1045-- O(n) space, where n is the number elements dropped.
1048{-# INLINE dropWhileEnd #-}
1049dropWhileEnd :: -- (IsStream t, Monad m) =>
1050 (a -> Bool) -> t m a -> t m a
1051dropWhileEnd = undefined -- fromStreamD $ D.dropWhileEnd n $ toStreamD m
1053-- | Like 'dropWhile' and 'dropWhileEnd' combined.
1055-- O(n) space, where n is the number elements dropped from the end.
1058{-# INLINE dropWhileAround #-}
1059dropWhileAround :: -- (IsStream t, Monad m) =>
1060 (a -> Bool) -> t m a -> t m a
1061dropWhileAround = undefined -- fromStreamD $ D.dropWhileAround n $ toStreamD m
1063------------------------------------------------------------------------------
1064-- Inserting Elements
1065------------------------------------------------------------------------------
1067-- | @insertBy cmp elem stream@ inserts @elem@ before the first element in
1068-- @stream@ that is less than @elem@ when compared using @cmp@.
1071-- insertBy cmp x = 'mergeBy' cmp ('yield' x)
1075-- > S.toList $ S.insertBy compare 2 $ S.fromList [1,3,5]
1080{-# INLINE insertBy #-}
1082 (IsStream t, Monad m) => (a -> a -> Ordering) -> a -> t m a -> t m a
1083insertBy cmp x m = fromStreamS $ S.insertBy cmp x (toStreamS m)
1085-- | Insert a pure value between successive elements of a stream.
1088-- > S.toList $ S.intersperse ',' $ S.fromList "hello"
1093{-# INLINE intersperse #-}
1094intersperse :: (IsStream t, MonadAsync m) => a -> t m a -> t m a
1095intersperse a = fromStreamS . S.intersperse a . toStreamS
1097-- | Insert a side effect before consuming an element of a stream except the
1101-- >>> S.drain $ S.trace putChar $ S.intersperseM_ (putChar '.') $ S.fromList "hello"
1106{-# INLINE intersperseM_ #-}
1107intersperseM_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
1108intersperseM_ m = fromStreamD . D.intersperseM_ m . toStreamD
1110-- | Intersperse a monadic action into the input stream after every @n@
1114-- > S.toList $ S.intersperseBySpan 2 (return ',') $ S.fromList "hello"
1119{-# INLINE intersperseBySpan #-}
1120intersperseBySpan :: -- IsStream t =>
1121 Int -> m a -> t m a -> t m a
1122intersperseBySpan _n _f _xs = undefined
1124-- | Insert an effect and its output after consuming an element of a stream.
1127-- >>> S.toList $ S.trace putChar $ S.intersperseSuffix (putChar '.' >> return ',') $ S.fromList "hello"
1128-- > h.,e.,l.,l.,o.,"h,e,l,l,o,"
1132{-# INLINE intersperseSuffix #-}
1133intersperseSuffix :: (IsStream t, MonadAsync m) => m a -> t m a -> t m a
1134intersperseSuffix m = fromStreamD . D.intersperseSuffix m . toStreamD
1136-- | Insert a side effect after consuming an element of a stream.
1139-- > S.mapM_ putChar $ S.intersperseSuffix_ (threadDelay 1000000) $ S.fromList "hello"
1144{-# INLINE intersperseSuffix_ #-}
1145intersperseSuffix_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
1146intersperseSuffix_ m = fromStreamD . D.intersperseSuffix_ m . toStreamD
1148-- XXX Use an offset argument, like tapOffsetEvery
1150-- | Like 'intersperseSuffix' but intersperses an effectful action into the
1151-- input stream after every @n@ elements and after the last element.
1154-- > S.toList $ S.intersperseSuffixBySpan 2 (return ',') $ S.fromList "hello"
1160{-# INLINE intersperseSuffixBySpan #-}
1161intersperseSuffixBySpan :: (IsStream t, MonadAsync m)
1162 => Int -> m a -> t m a -> t m a
1163intersperseSuffixBySpan n eff =
1164 fromStreamD . D.intersperseSuffixBySpan n eff . toStreamD
1166-- | Insert a side effect before consuming an element of a stream.
1169-- >>> S.toList $ S.trace putChar $ S.interspersePrefix_ (putChar '.' >> return ',') $ S.fromList "hello"
1170-- > .h.e.l.l.o"hello"
1173-- Same as 'trace_' but may be concurrent.
1179{-# INLINE interspersePrefix_ #-}
1180interspersePrefix_ :: (IsStream t, MonadAsync m) => m b -> t m a -> t m a
1181interspersePrefix_ m = mapM (\x -> void m >> return x)
1183------------------------------------------------------------------------------
1185------------------------------------------------------------------------------
1187-- Note: delay must be serial.
1189-- | Introduce a delay of specified seconds before consuming an element of the
1190-- stream except the first one.
1193-- >>> S.mapM_ print $ S.timestamped $ S.delay 1 $ S.enumerateFromTo 1 3
1194-- > (AbsTime (TimeSpec {sec = 2502706, nsec = 751137000}),1)
1195-- > (AbsTime (TimeSpec {sec = 2502707, nsec = 743535000}),2)
1196-- > (AbsTime (TimeSpec {sec = 2502708, nsec = 749758000}),3)
1202delay :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
1203delay n = intersperseM_ $ liftIO $ threadDelay $ round $ n * 1000000
1205-- Note: delay must be serial.
1207-- | Introduce a delay of specified seconds after consuming an element of a
1211-- >>> S.mapM_ print $ S.timestamped $ S.delayPost 1 $ S.enumerateFromTo 1 3
1212-- > (AbsTime (TimeSpec {sec = 2502826, nsec = 119030000}),1)
1213-- > (AbsTime (TimeSpec {sec = 2502827, nsec = 111393000}),2)
1214-- > (AbsTime (TimeSpec {sec = 2502828, nsec = 112221000}),3)
1219{-# INLINE delayPost #-}
1220delayPost :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
1221delayPost n = intersperseSuffix_ $ liftIO $ threadDelay $ round $ n * 1000000
1223-- Note: delay must be serial, that's why 'trace_' is used.
1225-- | Introduce a delay of specified seconds before consuming an element of a
1229-- >>> S.mapM_ print $ S.timestamped $ S.delayPre 1 $ S.enumerateFromTo 1 3
1230-- > (AbsTime (TimeSpec {sec = 2502207, nsec = 533177000}),1)
1231-- > (AbsTime (TimeSpec {sec = 2502208, nsec = 530859000}),2)
1232-- > (AbsTime (TimeSpec {sec = 2502209, nsec = 531619000}),3)
1237{-# INLINE delayPre #-}
1238delayPre :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
1239delayPre n = trace_ $ liftIO $ threadDelay $ round $ n * 1000000
1241------------------------------------------------------------------------------
1242-- Reorder in sequence
1243------------------------------------------------------------------------------
1245-- | Buffer until the next element in sequence arrives. The function argument
1246-- determines the difference in sequence numbers. This could be useful in
1247-- implementing sequenced streams, for example, TCP reassembly.
1251{-# INLINE reassembleBy #-}
1253 :: -- (IsStream t, Monad m) =>
1258reassembleBy = undefined
1260------------------------------------------------------------------------------
1262------------------------------------------------------------------------------
1265-- > indexed = S.postscanl' (\(i, _) x -> (i + 1, x)) (-1,undefined)
1266-- > indexed = S.zipWith (,) (S.enumerateFrom 0)
1268-- Pair each element in a stream with its index, starting from index 0.
1271-- > S.toList $ S.indexed $ S.fromList "hello"
1272-- [(0,'h'),(1,'e'),(2,'l'),(3,'l'),(4,'o')]
1276{-# INLINE indexed #-}
1277indexed :: (IsStream t, Monad m) => t m a -> t m (Int, a)
1278indexed = fromStreamD . D.indexed . toStreamD
1281-- > indexedR n = S.postscanl' (\(i, _) x -> (i - 1, x)) (n + 1,undefined)
1282-- > indexedR n = S.zipWith (,) (S.enumerateFromThen n (n - 1))
1284-- Pair each element in a stream with its index, starting from the
1285-- given index @n@ and counting down.
1288-- > S.toList $ S.indexedR 10 $ S.fromList "hello"
1289-- [(10,'h'),(9,'e'),(8,'l'),(7,'l'),(6,'o')]
1293{-# INLINE indexedR #-}
1294indexedR :: (IsStream t, Monad m) => Int -> t m a -> t m (Int, a)
1295indexedR n = fromStreamD . D.indexedR n . toStreamD
1297-------------------------------------------------------------------------------
1299-------------------------------------------------------------------------------
1301-- Note: The timestamp stream must be the second stream in the zip so that the
1302-- timestamp is generated after generating the stream element and not before.
1303-- If we do not do that then the following example will generate the same
1304-- timestamp for first two elements:
1306-- S.mapM_ print $ S.timestamped $ S.delay $ S.enumerateFromTo 1 3
1308-- | Pair each element in a stream with an absolute timestamp, using a clock of
1309-- specified granularity. The timestamp is generated just before the element
1313-- >>> S.mapM_ print $ S.timestampWith 0.01 $ S.delay 1 $ S.enumerateFromTo 1 3
1318{-# INLINE timestampWith #-}
1319timestampWith :: (IsStream t, MonadAsync m, Functor (t m))
1320 => Double -> t m a -> t m (AbsTime, a)
1321timestampWith g stream = Z.zipWith (flip (,)) stream (absTimesWith g)
1323-- TBD: check performance vs a custom implementation without using zipWith.
1327{-# INLINE timestamped #-}
1328timestamped :: (IsStream t, MonadAsync m, Functor (t m))
1329 => t m a -> t m (AbsTime, a)
1330timestamped = timestampWith 0.01
1332-- | Pair each element in a stream with relative times starting from 0, using a
1333-- clock with the specified granularity. The time is measured just before the
1334-- element is consumed.
1337-- >>> S.mapM_ print $ S.timeIndexWith 0.01 $ S.delay 1 $ S.enumerateFromTo 1 3
1342{-# INLINE timeIndexWith #-}
1343timeIndexWith :: (IsStream t, MonadAsync m, Functor (t m))
1344 => Double -> t m a -> t m (RelTime64, a)
1345timeIndexWith g stream = Z.zipWith (flip (,)) stream (relTimesWith g)
1347-- | Pair each element in a stream with relative times starting from 0, using a
1348-- 10 ms granularity clock. The time is measured just before the element is
1352-- >>> S.mapM_ print $ S.timeIndexed $ S.delay 1 $ S.enumerateFromTo 1 3
1353-- (RelTime64 (NanoSecond64 0),1)
1354-- (RelTime64 (NanoSecond64 996239000),2)
1355-- (RelTime64 (NanoSecond64 1996712000),3)
1360{-# INLINE timeIndexed #-}
1361timeIndexed :: (IsStream t, MonadAsync m, Functor (t m))
1362 => t m a -> t m (RelTime64, a)
1363timeIndexed = timeIndexWith 0.01
1365------------------------------------------------------------------------------
1367------------------------------------------------------------------------------
1369-- | Find all the indices where the value of the element in the stream is equal
1370-- to the given value.
1372-- > elemIndices a = findIndices (== a)
1375{-# INLINE elemIndices #-}
1376elemIndices :: (IsStream t, Eq a, Monad m) => a -> t m a -> t m Int
1377elemIndices a = findIndices (== a)
1379------------------------------------------------------------------------------
1381------------------------------------------------------------------------------
1383-- XXX this is not a one-to-one map so calling it map may not be right.
1384-- We can perhaps call it zipWithTail or rollWith.
1386-- | Apply a function on every two successive elements of a stream. If the
1387-- stream consists of a single element the output is an empty stream.
1389-- This is the stream equivalent of the list idiom @zipWith f xs (tail xs)@.
1393{-# INLINE rollingMap #-}
1394rollingMap :: (IsStream t, Monad m) => (a -> a -> b) -> t m a -> t m b
1395rollingMap f m = fromStreamD $ D.rollingMap f $ toStreamD m
1397-- | Like 'rollingMap' but with an effectful map function.
1401{-# INLINE rollingMapM #-}
1402rollingMapM :: (IsStream t, Monad m) => (a -> a -> m b) -> t m a -> t m b
1403rollingMapM f m = fromStreamD $ D.rollingMapM f $ toStreamD m
1405------------------------------------------------------------------------------
1407------------------------------------------------------------------------------
1409-- | Map a 'Maybe' returning function to a stream, filter out the 'Nothing'
1410-- elements, and return a stream of values extracted from 'Just'.
1415-- mapMaybe f = S.map 'fromJust' . S.filter 'isJust' . S.map f
1419{-# INLINE mapMaybe #-}
1420mapMaybe :: (IsStream t, Monad m) => (a -> Maybe b) -> t m a -> t m b
1421mapMaybe f m = fromStreamS $ S.mapMaybe f $ toStreamS m
1423-- | Like 'mapMaybe' but maps a monadic function.
1428-- mapMaybeM f = S.map 'fromJust' . S.filter 'isJust' . S.mapM f
1431-- /Concurrent (do not use with 'parallely' on infinite streams)/
1434{-# INLINE_EARLY mapMaybeM #-}
1435mapMaybeM :: (IsStream t, MonadAsync m, Functor (t m))
1436 => (a -> m (Maybe b)) -> t m a -> t m b
1437mapMaybeM f = fmap fromJust . filter isJust . K.mapM f
1439{-# RULES "mapMaybeM serial" mapMaybeM = mapMaybeMSerial #-}
1440{-# INLINE mapMaybeMSerial #-}
1441mapMaybeMSerial :: Monad m => (a -> m (Maybe b)) -> SerialT m a -> SerialT m b
1442mapMaybeMSerial f m = fromStreamD $ D.mapMaybeM f $ toStreamD m
1444-- | In a stream of 'Maybe's, discard 'Nothing's and unwrap 'Just's.
1448catMaybes :: (IsStream t, Monad m, Functor (t m)) => t m (Maybe a) -> t m a
1449catMaybes = fmap fromJust . filter isJust
1451------------------------------------------------------------------------------
1453------------------------------------------------------------------------------
1455-- | Discard 'Right's and unwrap 'Left's in an 'Either' stream.
1459lefts :: (IsStream t, Monad m, Functor (t m)) => t m (Either a b) -> t m a
1460lefts = fmap (fromLeft undefined) . filter isLeft
1462-- | Discard 'Left's and unwrap 'Right's in an 'Either' stream.
1466rights :: (IsStream t, Monad m, Functor (t m)) => t m (Either a b) -> t m b
1467rights = fmap (fromRight undefined) . filter isRight
1469------------------------------------------------------------------------------
1470-- Concurrent Application
1471------------------------------------------------------------------------------
1473-- | Parallel transform application operator; applies a stream transformation
1474-- function @t m a -> t m b@ to a stream @t m a@ concurrently; the input stream
1475-- is evaluated asynchronously in an independent thread yielding elements to a
1476-- buffer and the transformation function runs in another thread consuming the
1477-- input from the buffer. '|$' is just like regular function application
1478-- operator '$' except that it is concurrent.
1480-- If you read the signature as @(t m a -> t m b) -> (t m a -> t m b)@ you can
1481-- look at it as a transformation that converts a transform function to a
1482-- buffered concurrent transform function.
1484-- The following code prints a value every second even though each stage adds a
1490-- S.mapM (\\x -> threadDelay 1000000 >> print x)
1491-- |$ S.repeatM (threadDelay 1000000 >> return 1)
1496-- /Since: 0.3.0 ("Streamly")/
1500(|$) :: (IsStream t, MonadAsync m) => (t m a -> t m b) -> (t m a -> t m b)
1501-- (|$) f = f . Async.mkAsync
1502(|$) f = f . Par.mkParallel
1510{-# INLINE applyAsync #-}
1511applyAsync :: (IsStream t, MonadAsync m)
1512 => (t m a -> t m b) -> (t m a -> t m b)
1515-- | Parallel reverse function application operator for streams; just like the
1516-- regular reverse function application operator '&' except that it is
1521-- S.repeatM (threadDelay 1000000 >> return 1)
1522-- |& S.mapM (\\x -> threadDelay 1000000 >> print x)
1527-- /Since: 0.3.0 ("Streamly")/
1531(|&) :: (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