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.
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.Type (Fold (..))
220import Streamly.Internal.Data.Pipe.Type (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)
266-- >>> import Control.Concurrent (threadDelay)
267-- >>> import Data.Function ((&))
268-- >>> import Streamly.Prelude ((|$))
269-- >>> import Prelude hiding ( filter, drop, dropWhile, take, takeWhile, foldr, map, mapM, sequence, reverse, foldr1 , scanl, scanl1)
270-- >>> import qualified Streamly.Prelude as Stream
271-- >>> import Streamly.Internal.Data.Stream.IsStream as Stream
272-- >>> import qualified Streamly.Data.Fold as Fold
273-- >>> import qualified Streamly.Internal.Data.Fold as Fold
275------------------------------------------------------------------------------
277------------------------------------------------------------------------------
279-- | Use a 'Pipe' to transform a stream.
283{-# INLINE transform #-}
284transform :: (IsStream t, Monad m) => Pipe m a b -> t m a -> t m b
285transform pipe xs = fromStreamD $ D.transform pipe (toStreamD xs)
287------------------------------------------------------------------------------
288-- Transformation Folds
289------------------------------------------------------------------------------
291-- | Right fold to a streaming monad.
293-- > foldrS Stream.cons Stream.nil === id
295-- 'foldrS' can be used to perform stateless stream to stream transformations
296-- like map and filter in general. It can be coupled with a scan to perform
297-- stateful transformations. However, note that the custom map and filter
298-- routines can be much more efficient than this due to better stream fusion.
300-- >>> Stream.toList $ Stream.foldrS Stream.cons Stream.nil $ Stream.fromList [1..5]
303-- Find if any element in the stream is 'True':
305-- >>> 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)
308-- Map (+2) on odd elements and filter out the even elements:
310-- >>> 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)
313-- 'foldrM' can also be represented in terms of 'foldrS', however, the former
314-- is much more efficient:
316-- > foldrM f z s = runIdentityT $ foldrS (\x xs -> lift $ f x (runIdentityT xs)) (lift z) s
320foldrS :: IsStream t => (a -> t m b -> t m b) -> t m b -> t m a -> t m b
323-- | Right fold to a transformer monad. This is the most general right fold
324-- function. 'foldrS' is a special case of 'foldrT', however 'foldrS'
325-- implementation can be more efficient:
328-- > foldrM f z s = runIdentityT $ foldrT (\x xs -> lift $ f x (runIdentityT xs)) (lift z) s
330-- 'foldrT' can be used to translate streamly streams to other transformer
331-- monads e.g. to a different streaming type.
335foldrT :: (IsStream t, Monad m, Monad (s m), MonadTrans s)
336 => (a -> s m b -> s m b) -> s m b -> t m a -> s m b
337foldrT f z s = S.foldrT f z (toStreamS s)
339------------------------------------------------------------------------------
340-- Transformation by Mapping
341------------------------------------------------------------------------------
345-- mapM f = sequence . map f
348-- Apply a monadic function to each element of the stream and replace it with
349-- the output of the resulting action.
352-- >>> drain $ Stream.mapM putStr $ Stream.fromList ["a", "b", "c"]
356-- drain $ Stream.replicateM 10 (return 1)
357-- & (fromSerial . Stream.mapM (\x -> threadDelay 1000000 >> print x))
363-- > drain $ Stream.replicateM 10 (return 1)
364-- & (fromAsync . Stream.mapM (\x -> threadDelay 1000000 >> print x))
367-- /Concurrent (do not use with 'fromParallel' on infinite streams)/
370{-# INLINE_EARLY mapM #-}
371mapM :: (IsStream t, MonadAsync m) => (a -> m b) -> t m a -> t m b
374{-# RULES "mapM serial" mapM = mapMSerial #-}
375{-# INLINE mapMSerial #-}
376mapMSerial :: Monad m => (a -> m b) -> SerialT m a -> SerialT m b
377mapMSerial = Serial.mapM
384-- Replace the elements of a stream of monadic actions with the outputs of
388-- >>> drain $ Stream.sequence $ Stream.fromList [putStr "a", putStr "b", putStrLn "c"]
392-- drain $ Stream.replicateM 10 (return $ threadDelay 1000000 >> print 1)
393-- & (fromSerial . Stream.sequence)
400-- drain $ Stream.replicateM 10 (return $ threadDelay 1000000 >> print 1)
401-- & (fromAsync . Stream.sequence)
409-- /Concurrent (do not use with 'fromParallel' on infinite streams)/
412{-# INLINE sequence #-}
413sequence :: (IsStream t, MonadAsync m) => t m (m a) -> t m a
414sequence m = fromStreamS $ S.sequence (toStreamS m)
416------------------------------------------------------------------------------
417-- Mapping side effects
418------------------------------------------------------------------------------
420-- | Tap the data flowing through a stream into a 'Fold'. For example, you may
421-- add a tap to log the contents flowing through the stream. The fold is used
422-- only for effects, its result is discarded.
427-- -----stream m a ---------------stream m a-----
431-- >>> Stream.drain $ Stream.tap (Fold.drainBy print) (Stream.enumerateFromTo 1 2)
435-- Compare with 'trace'.
439tap :: (IsStream t, Monad m) => FL.Fold m a b -> t m a -> t m a
440tap f xs = D.fromStreamD $ D.tap f (D.toStreamD xs)
442-- XXX Remove this. It can be expressed in terms of Fold.sampleFromThen.
444-- | @tapOffsetEvery offset n@ taps every @n@th element in the stream
445-- starting at @offset@. @offset@ can be between @0@ and @n - 1@. Offset 0
446-- means start at the first element in the stream. If the offset is outside
447-- this range then @offset `mod` n@ is used as offset.
449-- >>> Stream.drain $ Stream.tapOffsetEvery 0 2 (Fold.rmapM print Fold.toList) $ Stream.enumerateFromTo 0 10
455{-# INLINE tapOffsetEvery #-}
456tapOffsetEvery :: (IsStream t, Monad m)
457 => Int -> Int -> FL.Fold m a b -> t m a -> t m a
458tapOffsetEvery offset n f xs =
459 D.fromStreamD $ D.tapOffsetEvery offset n f (D.toStreamD xs)
461-- | Redirect a copy of the stream to a supplied fold and run it concurrently
462-- in an independent thread. The fold may buffer some elements. The buffer size
463-- is determined by the prevailing 'maxBuffer' setting.
468-- -----stream m a ---------------stream m a-----
473-- >>> Stream.drain $ Stream.tapAsync (Fold.drainBy print) (Stream.enumerateFromTo 1 2)
479-- Exceptions from the concurrently running fold are propagated to the current
480-- computation. Note that, because of buffering in the fold, exceptions may be
481-- delayed and may not correspond to the current element being processed in the
482-- parent stream, but we guarantee that before the parent stream stops the tap
483-- finishes and all exceptions from it are drained.
486-- Compare with 'tap'.
489{-# INLINE tapAsync #-}
490tapAsync :: (IsStream t, MonadAsync m) => FL.Fold m a b -> t m a -> t m a
491tapAsync f xs = D.fromStreamD $ Par.tapAsyncF f (D.toStreamD xs)
493-- | @pollCounts predicate transform fold stream@ counts those elements in the
494-- stream that pass the @predicate@. The resulting count stream is sent to
495-- another thread which transforms it using @transform@ and then folds it using
496-- @fold@. The thread is automatically cleaned up if the stream stops or
497-- aborts due to exception.
499-- For example, to print the count of elements processed every second:
502-- > Stream.drain $ Stream.pollCounts (const True) (Stream.rollingMap (-) . Stream.delayPost 1) (FLold.drainBy print)
503-- $ Stream.enumerateFrom 0
506-- Note: This may not work correctly on 32-bit machines.
510{-# INLINE pollCounts #-}
512 (IsStream t, MonadAsync m)
514 -> (t m Int -> t m Int)
518pollCounts predicate transf f xs =
520 $ D.pollCounts predicate (D.toStreamD . transf . D.fromStreamD) f
523-- | Calls the supplied function with the number of elements consumed
524-- every @n@ seconds. The given function is run in a separate thread
525-- until the end of the stream. In case there is an exception in the
526-- stream the thread is killed during the next major GC.
528-- Note: The action is not guaranteed to run if the main thread exits.
531-- > delay n = threadDelay (round $ n * 1000000) >> return n
532-- > Stream.toList $ Stream.tapRate 2 (\n -> print $ show n ++ " elements processed") (delay 1 Stream.|: delay 0.5 Stream.|: delay 0.5 Stream.|: Stream.nil)
533-- "2 elements processed"
535-- "1 elements processed"
538-- Note: This may not work correctly on 32-bit machines.
541{-# INLINE tapRate #-}
543 (IsStream t, MonadAsync m, MonadCatch m)
548tapRate n f xs = D.fromStreamD $ D.tapRate n f $ D.toStreamD xs
550-- | Apply a monadic function to each element flowing through the stream and
551-- discard the results.
554-- >>> Stream.drain $ Stream.trace print (Stream.enumerateFromTo 1 2)
560-- Compare with 'tap'.
564trace :: (IsStream t, MonadAsync m) => (a -> m b) -> t m a -> t m a
565trace f = mapM (\x -> void (f x) >> return x)
567-- | Perform a side effect before yielding each element of the stream and
568-- discard the results.
571-- >>> Stream.drain $ Stream.trace_ (print "got here") (Stream.enumerateFromTo 1 2)
577-- Same as 'interspersePrefix_' but always serial.
583trace_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
584trace_ eff = Serial.mapM (\x -> eff >> return x)
586------------------------------------------------------------------------------
587-- Scanning with a Fold
588------------------------------------------------------------------------------
590-- | Scan a stream using the given monadic fold.
592-- >>> Stream.toList $ Stream.takeWhile (< 10) $ Stream.scan Fold.sum (Stream.fromList [1..10])
597scan :: (IsStream t, Monad m) => Fold m a b -> t m a -> t m b
600-- | Postscan a stream using the given monadic fold.
602-- The following example extracts the input stream up to a point where the
603-- running average of elements is no more than 10:
605-- >>> import Data.Maybe (fromJust)
606-- >>> let avg = Fold.teeWith (/) Fold.sum (fmap fromIntegral Fold.length)
609-- $ Stream.map (fromJust . fst)
610-- $ Stream.takeWhile (\(_,x) -> x <= 10)
611-- $ Stream.postscan (Fold.tee Fold.last avg) (Stream.enumerateFromTo 1.0 100.0)
613-- [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]
616{-# INLINE postscan #-}
617postscan :: (IsStream t, Monad m) => Fold m a b -> t m a -> t m b
618postscan = P.postscanOnce
620------------------------------------------------------------------------------
621-- Scanning - Transformation by Folding
622------------------------------------------------------------------------------
624-- XXX It may be useful to have a version of scan where we can keep the
625-- accumulator independent of the value emitted. So that we do not necessarily
626-- have to keep a value in the accumulator which we are not using. We can pass
627-- an extraction function that will take the accumulator and the current value
628-- of the element and emit the next value in the stream. That will also make it
629-- possible to modify the accumulator after using it. In fact, the step function
630-- can return new accumulator and the value to be emitted. The signature would
631-- be more like mapAccumL. Or we can change the signature of scanx to
634-- | Strict left scan with an extraction function. Like 'scanl'', but applies a
635-- user supplied extraction function (the third argument) at each step. This is
636-- designed to work with the @foldl@ library. The suffix @x@ is a mnemonic for
641-- /Since: 0.7.0 (Monad m constraint)/
642{-# DEPRECATED scanx "Please use scanl followed by map instead." #-}
644scanx :: (IsStream t, Monad m) => (x -> a -> x) -> x -> (x -> b) -> t m a -> t m b
647-- XXX this needs to be concurrent
648-- XXX because of the use of D.cons for appending, scanlM' has quadratic
649-- complexity when iterated over a stream. We should use StreamK style scanlM'
650-- for linear performance on iteration.
652-- | Like 'scanl'' but with a monadic step function and a monadic seed.
656-- /Since: 0.8.0 (signature change)/
657{-# INLINE scanlM' #-}
658scanlM' :: (IsStream t, Monad m) => (b -> a -> m b) -> m b -> t m a -> t m b
659scanlM' step begin m = fromStreamD $ D.scanlM' step begin $ toStreamD m
661-- XXX because of the use of D.cons for appending, scanl' has quadratic
662-- complexity when iterated over a stream. We should use StreamK style scanlM'
663-- for linear performance on iteration.
665-- | Strict left scan. Like 'map', 'scanl'' too is a one to one transformation,
666-- however it adds an extra element.
669-- >>> Stream.toList $ Stream.scanl' (+) 0 $ fromList [1,2,3,4]
675-- >>> Stream.toList $ Stream.scanl' (flip (:)) [] $ Stream.fromList [1,2,3,4]
676-- [[],[1],[2,1],[3,2,1],[4,3,2,1]]
680-- The output of 'scanl'' is the initial value of the accumulator followed by
681-- all the intermediate steps and the final result of 'foldl''.
683-- By streaming the accumulated state after each fold step, we can share the
684-- state across multiple stages of stream composition. Each stage can modify or
685-- extend the state, do some processing with it and emit it for the next stage,
686-- thus modularizing the stream processing. This can be useful in
687-- stateful or event-driven programming.
689-- Consider the following monolithic example, computing the sum and the product
690-- of the elements in a stream in one go using a @foldl'@:
693-- >>> Stream.foldl' (\(s, p) x -> (s + x, p * x)) (0,1) $ Stream.fromList [1,2,3,4]
698-- Using @scanl'@ we can make it modular by computing the sum in the first
699-- stage and passing it down to the next stage for computing the product:
703-- Stream.foldl' (\(_, p) (s, x) -> (s, p * x)) (0,1)
704-- $ Stream.scanl' (\(s, _) x -> (s + x, x)) (0,1)
705-- $ Stream.fromList [1,2,3,4]
711-- IMPORTANT: 'scanl'' evaluates the accumulator to WHNF. To avoid building
712-- lazy expressions inside the accumulator, it is recommended that a strict
713-- data structure is used for accumulator.
715-- See also: 'usingStateT'
719scanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
720scanl' step z m = fromStreamS $ S.scanl' step z $ toStreamS m
722-- | Like 'scanl'' but does not stream the initial value of the accumulator.
724-- > postscanl' f z xs = Stream.drop 1 $ Stream.scanl' f z xs
727{-# INLINE postscanl' #-}
728postscanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
729postscanl' step z m = fromStreamD $ D.postscanl' step z $ toStreamD m
731-- XXX prescanl does not sound very useful, enable only if there is a
732-- compelling use case.
734-- | Like scanl' but does not stream the final value of the accumulator.
737{-# INLINE prescanl' #-}
738prescanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
739prescanl' step z m = fromStreamD $ D.prescanl' step z $ toStreamD m
741-- XXX this needs to be concurrent
742-- | Like prescanl' but with a monadic step function and a monadic seed.
745{-# INLINE prescanlM' #-}
746prescanlM' :: (IsStream t, Monad m) => (b -> a -> m b) -> m b -> t m a -> t m b
747prescanlM' step z m = fromStreamD $ D.prescanlM' step z $ toStreamD m
749-- XXX this needs to be concurrent
750-- | Like 'scanl1'' but with a monadic step function.
753{-# INLINE scanl1M' #-}
754scanl1M' :: (IsStream t, Monad m) => (a -> a -> m a) -> t m a -> t m a
755scanl1M' step m = fromStreamD $ D.scanl1M' step $ toStreamD m
757-- | Like 'scanl'' but for a non-empty stream. The first element of the stream
758-- is used as the initial value of the accumulator. Does nothing if the stream
762-- >>> Stream.toList $ Stream.scanl1' (+) $ fromList [1,2,3,4]
768{-# INLINE scanl1' #-}
769scanl1' :: (IsStream t, Monad m) => (a -> a -> a) -> t m a -> t m a
770scanl1' step m = fromStreamD $ D.scanl1' step $ toStreamD m
772------------------------------------------------------------------------------
774------------------------------------------------------------------------------
776-- | Modify a @t m a -> t m a@ stream transformation that accepts a predicate
777-- @(a -> b)@ to accept @((s, a) -> b)@ instead, provided a transformation @t m
778-- a -> t m (s, a)@. Convenient to filter with index or time.
781-- filterWithIndex = with indexed filter
782-- filterWithAbsTime = with timestamped filter
783-- filterWithRelTime = with timeIndexed filter
788with :: forall (t :: (Type -> Type) -> Type -> Type) m a b s. Functor (t m) =>
789 (t m a -> t m (s, a))
790 -> (((s, a) -> b) -> t m (s, a) -> t m (s, a))
791 -> (((s, a) -> b) -> t m a -> t m a)
792with f comb g = fmap snd . comb g . f
794-- | Include only those elements that pass a predicate.
798#if __GLASGOW_HASKELL__ != 802
799-- GHC 8.2.2 crashes with this code, when used with "stack"
800filter :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m a
801filter p m = fromStreamS $ S.filter p $ toStreamS m
803filter :: IsStream t => (a -> Bool) -> t m a -> t m a
807-- | Same as 'filter' but with a monadic predicate.
810{-# INLINE filterM #-}
811filterM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
812filterM p m = fromStreamD $ D.filterM p $ toStreamD m
814-- | Drop repeated elements that are adjacent to each other using the supplied
815-- comparison function.
817-- @uniq = uniqBy (==)
819-- To strip duplicate path separators:
822-- f x y = x == '/' && x == y
823-- Stream.toList $ Stream.uniqBy f $ Stream.fromList "//a//b"
834uniqBy :: (IsStream t, Monad m, Functor (t m)) =>
835 (a -> a -> Bool) -> t m a -> t m a
837 catMaybes . rollingMap (\x y -> if x `eq` y then Nothing else Just y)
839-- | Drop repeated elements that are adjacent to each other.
843uniq :: (Eq a, IsStream t, Monad m) => t m a -> t m a
844uniq = fromStreamD . D.uniq . toStreamD
846-- | Strip all leading and trailing occurrences of an element passing a
847-- predicate and make all other consecutive occurrences uniq.
850-- prune p = dropWhileAround p $ uniqBy (x y -> p x && p y)
854-- > Stream.prune isSpace (Stream.fromList " hello world! ")
864 -- (IsStream t, Monad m, Eq a) =>
865 (a -> Bool) -> t m a -> t m a
866prune = error "Not implemented yet!"
868-- Possible implementation:
870-- Stream.catMaybes . Stream.parseMany (Parser.groupBy (==) Fold.repeated)@
872-- 'Fold.repeated' should return 'Just' when repeated, and 'Nothing' for a
875-- | Emit only repeated elements, once.
878repeated :: -- (IsStream t, Monad m, Eq a) =>
882-- We can have more efficient implementations for nubOrd and nubInt by using
883-- Set and IntSet to find/remove duplication. For Hashable we can use a
884-- hashmap. Use rewrite rules to specialize to more efficient impls.
886-- | Drop repeated elements anywhere in the stream.
888-- /Caution: not scalable for infinite streams/
890-- /See also: nubWindowBy/
895nubBy :: -- (IsStream t, Monad m) =>
896 (a -> a -> Bool) -> t m a -> t m a
897nubBy = undefined -- fromStreamD . D.nubBy . toStreamD
899-- | Drop repeated elements within the specified tumbling window in the stream.
901-- @nubBy = nubWindowBy maxBound@
905{-# INLINE nubWindowBy #-}
906nubWindowBy :: -- (IsStream t, Monad m) =>
907 Int -> (a -> a -> Bool) -> t m a -> t m a
908nubWindowBy = undefined -- fromStreamD . D.nubWithinBy . toStreamD
910-- | Deletes the first occurrence of the element in the stream that satisfies
911-- the given equality predicate.
914-- >>> Stream.toList $ Stream.deleteBy (==) 3 $ Stream.fromList [1,3,3,5]
920{-# INLINE deleteBy #-}
921deleteBy :: (IsStream t, Monad m) => (a -> a -> Bool) -> a -> t m a -> t m a
922deleteBy cmp x m = fromStreamS $ S.deleteBy cmp x (toStreamS m)
924------------------------------------------------------------------------------
926------------------------------------------------------------------------------
928-- XXX We could use 'maxBuffer Block/Drop/Rotate/Sample' instead. However we
929-- may want to have the evaluation rate independent of the sampling rate. To
930-- support that we can decouple evaluation and sampling in independent stages.
931-- The sampling stage would strictly evaluate and sample, the evaluation stage
932-- would control the evaluation rate.
934-- | Evaluate the input stream continuously and keep only the oldest @n@
935-- elements in the buffer, discard the new ones when the buffer is full. When
936-- the output stream is evaluated it consumes the values from the buffer in a
941{-# INLINE sampleOld #-}
942sampleOld :: -- (IsStream t, Monad m) =>
943 Int -> t m a -> t m a
946-- | Evaluate the input stream continuously and keep only the latest @n@
947-- elements in a ring buffer, keep discarding the older ones to make space for
948-- the new ones. When the output stream is evaluated it consumes the values
949-- from the buffer in a FIFO manner.
953{-# INLINE sampleNew #-}
954sampleNew :: -- (IsStream t, Monad m) =>
955 Int -> t m a -> t m a
958-- | Like 'sampleNew' but samples at uniform intervals to match the consumer
959-- rate. Note that 'sampleNew' leads to non-uniform sampling depending on the
964{-# INLINE sampleRate #-}
965sampleRate :: -- (IsStream t, Monad m) =>
966 Double -> t m a -> t m a
967sampleRate = undefined
969------------------------------------------------------------------------------
971------------------------------------------------------------------------------
973-- | Same as 'takeWhile' but with a monadic predicate.
976{-# INLINE takeWhileM #-}
977takeWhileM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
978takeWhileM p m = fromStreamD $ D.takeWhileM p $ toStreamD m
980-- See the lastN fold for impl hints. Use a Data.Array based ring buffer.
982-- takeLast n = Stream.concatM . fmap Array.toStream . fold Fold.lastN
984-- | Take @n@ elements at the end of the stream.
986-- O(n) space, where n is the number elements taken.
989{-# INLINE takeLast #-}
990takeLast :: -- (IsStream t, Monad m) =>
991 Int -> t m a -> t m a
992takeLast = undefined -- fromStreamD $ D.takeLast n $ toStreamD m
994-- | Take time interval @i@ seconds at the end of the stream.
996-- O(n) space, where n is the number elements taken.
999{-# INLINE takeLastInterval #-}
1000takeLastInterval :: -- (IsStream t, Monad m) =>
1001 Double -> t m a -> t m a
1002takeLastInterval = undefined -- fromStreamD $ D.takeLast n $ toStreamD m
1004-- | Take all consecutive elements at the end of the stream for which the
1005-- predicate is true.
1007-- O(n) space, where n is the number elements taken.
1010{-# INLINE takeWhileLast #-}
1011takeWhileLast :: -- (IsStream t, Monad m) =>
1012 (a -> Bool) -> t m a -> t m a
1013takeWhileLast = undefined -- fromStreamD $ D.takeWhileLast n $ toStreamD m
1015-- | Like 'takeWhile' and 'takeWhileLast' combined.
1017-- O(n) space, where n is the number elements taken from the end.
1020{-# INLINE takeWhileAround #-}
1021takeWhileAround :: -- (IsStream t, Monad m) =>
1022 (a -> Bool) -> t m a -> t m a
1023takeWhileAround = undefined -- fromStreamD $ D.takeWhileAround n $ toStreamD m
1025-- | @takeInterval duration@ yields stream elements upto specified time
1026-- @duration@. The duration starts when the stream is evaluated for the first
1027-- time, before the first element is yielded. The time duration is checked
1028-- before generating each element, if the duration has expired the stream
1031-- The total time taken in executing the stream is guaranteed to be /at least/
1032-- @duration@, however, because the duration is checked before generating an
1033-- element, the upper bound is indeterminate and depends on the time taken in
1034-- generating and processing the last element.
1036-- No element is yielded if the duration is zero. At least one element is
1037-- yielded if the duration is non-zero.
1041{-# INLINE takeInterval #-}
1042takeInterval ::(MonadIO m, IsStream t, TimeUnit64 d) => d -> t m a -> t m a
1043takeInterval d = fromStreamD . D.takeByTime d . toStreamD
1045-- | Drop elements in the stream as long as the predicate succeeds and then
1046-- take the rest of the stream.
1049{-# INLINE dropWhile #-}
1050dropWhile :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m a
1051dropWhile p m = fromStreamS $ S.dropWhile p $ toStreamS m
1053-- | Same as 'dropWhile' but with a monadic predicate.
1056{-# INLINE dropWhileM #-}
1057dropWhileM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
1058dropWhileM p m = fromStreamD $ D.dropWhileM p $ toStreamD m
1060-- | @dropInterval duration@ drops stream elements until specified @duration@ has
1061-- passed. The duration begins when the stream is evaluated for the first
1062-- time. The time duration is checked /after/ generating a stream element, the
1063-- element is yielded if the duration has expired otherwise it is dropped.
1065-- The time elapsed before starting to generate the first element is /at most/
1066-- @duration@, however, because the duration expiry is checked after the
1067-- element is generated, the lower bound is indeterminate and depends on the
1068-- time taken in generating an element.
1070-- All elements are yielded if the duration is zero.
1074{-# INLINE dropInterval #-}
1075dropInterval ::(MonadIO m, IsStream t, TimeUnit64 d) => d -> t m a -> t m a
1076dropInterval d = fromStreamD . D.dropByTime d . toStreamD
1078-- | Drop @n@ elements at the end of the stream.
1080-- O(n) space, where n is the number elements dropped.
1083{-# INLINE dropLast #-}
1084dropLast :: -- (IsStream t, Monad m) =>
1085 Int -> t m a -> t m a
1086dropLast = undefined -- fromStreamD $ D.dropLast n $ toStreamD m
1088-- | Drop time interval @i@ seconds at the end of the stream.
1090-- O(n) space, where n is the number elements dropped.
1093{-# INLINE dropLastInterval #-}
1094dropLastInterval :: -- (IsStream t, Monad m) =>
1095 Int -> t m a -> t m a
1096dropLastInterval = undefined
1098-- | Drop all consecutive elements at the end of the stream for which the
1099-- predicate is true.
1101-- O(n) space, where n is the number elements dropped.
1104{-# INLINE dropWhileLast #-}
1105dropWhileLast :: -- (IsStream t, Monad m) =>
1106 (a -> Bool) -> t m a -> t m a
1107dropWhileLast = undefined -- fromStreamD $ D.dropWhileLast n $ toStreamD m
1109-- | Like 'dropWhile' and 'dropWhileLast' combined.
1111-- O(n) space, where n is the number elements dropped from the end.
1114{-# INLINE dropWhileAround #-}
1115dropWhileAround :: -- (IsStream t, Monad m) =>
1116 (a -> Bool) -> t m a -> t m a
1117dropWhileAround = undefined -- fromStreamD $ D.dropWhileAround n $ toStreamD m
1119------------------------------------------------------------------------------
1120-- Inserting Elements
1121------------------------------------------------------------------------------
1123-- | @insertBy cmp elem stream@ inserts @elem@ before the first element in
1124-- @stream@ that is less than @elem@ when compared using @cmp@.
1127-- insertBy cmp x = 'mergeBy' cmp ('fromPure' x)
1131-- >>> Stream.toList $ Stream.insertBy compare 2 $ Stream.fromList [1,3,5]
1137{-# INLINE insertBy #-}
1139 (IsStream t, Monad m) => (a -> a -> Ordering) -> a -> t m a -> t m a
1140insertBy cmp x m = fromStreamS $ S.insertBy cmp x (toStreamS m)
1142-- | Insert a pure value between successive elements of a stream.
1144-- >>> Stream.toList $ Stream.intersperse ',' $ Stream.fromList "hello"
1148{-# INLINE intersperse #-}
1149intersperse :: (IsStream t, MonadAsync m) => a -> t m a -> t m a
1150intersperse a = fromStreamS . S.intersperse a . toStreamS
1152-- | Insert a side effect before consuming an element of a stream except the
1155-- >>> Stream.drain $ Stream.trace putChar $ Stream.intersperseM_ (putChar '.') $ Stream.fromList "hello"
1159{-# INLINE intersperseM_ #-}
1160intersperseM_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
1161intersperseM_ m = fromStreamD . D.intersperseM_ m . toStreamD
1163-- | Intersperse a monadic action into the input stream after every @n@
1167-- > Stream.toList $ Stream.intersperseBySpan 2 (return ',') $ Stream.fromList "hello"
1173{-# INLINE intersperseBySpan #-}
1174intersperseBySpan :: -- IsStream t =>
1175 Int -> m a -> t m a -> t m a
1176intersperseBySpan _n _f _xs = undefined
1178-- | Insert an effect and its output after consuming an element of a stream.
1180-- >>> Stream.toList $ Stream.trace putChar $ intersperseSuffix (putChar '.' >> return ',') $ Stream.fromList "hello"
1181-- h.,e.,l.,l.,o.,"h,e,l,l,o,"
1184{-# INLINE intersperseSuffix #-}
1185intersperseSuffix :: (IsStream t, Monad m) => m a -> t m a -> t m a
1186intersperseSuffix m = fromStreamD . D.intersperseSuffix m . toStreamD
1188-- | Insert a side effect after consuming an element of a stream.
1191-- >>> Stream.mapM_ putChar $ Stream.intersperseSuffix_ (threadDelay 1000000) $ Stream.fromList "hello"
1198{-# INLINE intersperseSuffix_ #-}
1199intersperseSuffix_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
1200intersperseSuffix_ m = fromStreamD . D.intersperseSuffix_ m . toStreamD
1202-- XXX Use an offset argument, like tapOffsetEvery
1204-- | Like 'intersperseSuffix' but intersperses an effectful action into the
1205-- input stream after every @n@ elements and after the last element.
1207-- >>> Stream.toList $ Stream.intersperseSuffixBySpan 2 (return ',') $ Stream.fromList "hello"
1212{-# INLINE intersperseSuffixBySpan #-}
1213intersperseSuffixBySpan :: (IsStream t, Monad m)
1214 => Int -> m a -> t m a -> t m a
1215intersperseSuffixBySpan n eff =
1216 fromStreamD . D.intersperseSuffixBySpan n eff . toStreamD
1218-- | Insert a side effect before consuming an element of a stream.
1220-- >>> Stream.toList $ Stream.trace putChar $ Stream.interspersePrefix_ (putChar '.' >> return ',') $ Stream.fromList "hello"
1223-- Same as 'trace_' but may be concurrent.
1229{-# INLINE interspersePrefix_ #-}
1230interspersePrefix_ :: (IsStream t, MonadAsync m) => m b -> t m a -> t m a
1231interspersePrefix_ m = mapM (\x -> void m >> return x)
1233------------------------------------------------------------------------------
1235------------------------------------------------------------------------------
1237-- Note: delay must be serial.
1239-- | Introduce a delay of specified seconds before consuming an element of the
1240-- stream except the first one.
1242-- >>> Stream.mapM_ print $ Stream.timestamped $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
1243-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),1)
1244-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),2)
1245-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),3)
1250delay :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
1251delay n = intersperseM_ $ liftIO $ threadDelay $ round $ n * 1000000
1253-- Note: delay must be serial.
1255-- | Introduce a delay of specified seconds after consuming an element of a
1258-- >>> Stream.mapM_ print $ Stream.timestamped $ Stream.delayPost 1 $ Stream.enumerateFromTo 1 3
1259-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),1)
1260-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),2)
1261-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),3)
1265{-# INLINE delayPost #-}
1266delayPost :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
1267delayPost n = intersperseSuffix_ $ liftIO $ threadDelay $ round $ n * 1000000
1269-- Note: delay must be serial, that's why 'trace_' is used.
1271-- | Introduce a delay of specified seconds before consuming an element of a
1274-- >>> Stream.mapM_ print $ Stream.timestamped $ Stream.delayPre 1 $ Stream.enumerateFromTo 1 3
1275-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),1)
1276-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),2)
1277-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),3)
1281{-# INLINE delayPre #-}
1282delayPre :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
1283delayPre n = trace_ $ liftIO $ threadDelay $ round $ n * 1000000
1285------------------------------------------------------------------------------
1286-- Reorder in sequence
1287------------------------------------------------------------------------------
1289-- | Buffer until the next element in sequence arrives. The function argument
1290-- determines the difference in sequence numbers. This could be useful in
1291-- implementing sequenced streams, for example, TCP reassembly.
1295{-# INLINE reassembleBy #-}
1297 :: -- (IsStream t, Monad m) =>
1302reassembleBy = undefined
1304------------------------------------------------------------------------------
1306------------------------------------------------------------------------------
1309-- > indexed = Stream.postscanl' (\(i, _) x -> (i + 1, x)) (-1,undefined)
1310-- > indexed = Stream.zipWith (,) (Stream.enumerateFrom 0)
1312-- Pair each element in a stream with its index, starting from index 0.
1314-- >>> Stream.toList $ Stream.indexed $ Stream.fromList "hello"
1315-- [(0,'h'),(1,'e'),(2,'l'),(3,'l'),(4,'o')]
1318{-# INLINE indexed #-}
1319indexed :: (IsStream t, Monad m) => t m a -> t m (Int, a)
1320indexed = fromStreamD . D.indexed . toStreamD
1323-- > indexedR n = Stream.postscanl' (\(i, _) x -> (i - 1, x)) (n + 1,undefined)
1324-- > indexedR n = Stream.zipWith (,) (Stream.enumerateFromThen n (n - 1))
1326-- Pair each element in a stream with its index, starting from the
1327-- given index @n@ and counting down.
1329-- >>> Stream.toList $ Stream.indexedR 10 $ Stream.fromList "hello"
1330-- [(10,'h'),(9,'e'),(8,'l'),(7,'l'),(6,'o')]
1333{-# INLINE indexedR #-}
1334indexedR :: (IsStream t, Monad m) => Int -> t m a -> t m (Int, a)
1335indexedR n = fromStreamD . D.indexedR n . toStreamD
1337-------------------------------------------------------------------------------
1339-------------------------------------------------------------------------------
1341-- Note: The timestamp stream must be the second stream in the zip so that the
1342-- timestamp is generated after generating the stream element and not before.
1343-- If we do not do that then the following example will generate the same
1344-- timestamp for first two elements:
1346-- Stream.mapM_ print $ Stream.timestamped $ Stream.delay $ Stream.enumerateFromTo 1 3
1348-- | Pair each element in a stream with an absolute timestamp, using a clock of
1349-- specified granularity. The timestamp is generated just before the element
1352-- >>> Stream.mapM_ print $ Stream.timestampWith 0.01 $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
1353-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),1)
1354-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),2)
1355-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),3)
1359{-# INLINE timestampWith #-}
1360timestampWith :: (IsStream t, MonadAsync m, Functor (t m))
1361 => Double -> t m a -> t m (AbsTime, a)
1362timestampWith g stream = Z.zipWith (flip (,)) stream (absTimesWith g)
1364-- TBD: check performance vs a custom implementation without using zipWith.
1368{-# INLINE timestamped #-}
1369timestamped :: (IsStream t, MonadAsync m, Functor (t m))
1370 => t m a -> t m (AbsTime, a)
1371timestamped = timestampWith 0.01
1373-- | Pair each element in a stream with relative times starting from 0, using a
1374-- clock with the specified granularity. The time is measured just before the
1375-- element is consumed.
1377-- >>> Stream.mapM_ print $ Stream.timeIndexWith 0.01 $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
1378-- (RelTime64 (NanoSecond64 ...),1)
1379-- (RelTime64 (NanoSecond64 ...),2)
1380-- (RelTime64 (NanoSecond64 ...),3)
1384{-# INLINE timeIndexWith #-}
1385timeIndexWith :: (IsStream t, MonadAsync m, Functor (t m))
1386 => Double -> t m a -> t m (RelTime64, a)
1387timeIndexWith g stream = Z.zipWith (flip (,)) stream (relTimesWith g)
1389-- | Pair each element in a stream with relative times starting from 0, using a
1390-- 10 ms granularity clock. The time is measured just before the element is
1393-- >>> Stream.mapM_ print $ Stream.timeIndexed $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
1394-- (RelTime64 (NanoSecond64 ...),1)
1395-- (RelTime64 (NanoSecond64 ...),2)
1396-- (RelTime64 (NanoSecond64 ...),3)
1400{-# INLINE timeIndexed #-}
1401timeIndexed :: (IsStream t, MonadAsync m, Functor (t m))
1402 => t m a -> t m (RelTime64, a)
1403timeIndexed = timeIndexWith 0.01
1405------------------------------------------------------------------------------
1407------------------------------------------------------------------------------
1409-- | Find all the indices where the value of the element in the stream is equal
1410-- to the given value.
1412-- > elemIndices a = findIndices (== a)
1415{-# INLINE elemIndices #-}
1416elemIndices :: (IsStream t, Eq a, Monad m) => a -> t m a -> t m Int
1417elemIndices a = findIndices (== a)
1419------------------------------------------------------------------------------
1421------------------------------------------------------------------------------
1423-- XXX this is not a one-to-one map so calling it map may not be right.
1424-- We can perhaps call it zipWithTail or rollWith.
1426-- | Apply a function on every two successive elements of a stream. If the
1427-- stream consists of a single element the output is an empty stream.
1429-- This is the stream equivalent of the list idiom @zipWith f xs (tail xs)@.
1433{-# INLINE rollingMap #-}
1434rollingMap :: (IsStream t, Monad m) => (a -> a -> b) -> t m a -> t m b
1435rollingMap f m = fromStreamD $ D.rollingMap f $ toStreamD m
1437-- | Like 'rollingMap' but with an effectful map function.
1441{-# INLINE rollingMapM #-}
1442rollingMapM :: (IsStream t, Monad m) => (a -> a -> m b) -> t m a -> t m b
1443rollingMapM f m = fromStreamD $ D.rollingMapM f $ toStreamD m
1445------------------------------------------------------------------------------
1447------------------------------------------------------------------------------
1449-- | Map a 'Maybe' returning function to a stream, filter out the 'Nothing'
1450-- elements, and return a stream of values extracted from 'Just'.
1455-- mapMaybe f = Stream.map 'fromJust' . Stream.filter 'isJust' . Stream.map f
1459{-# INLINE mapMaybe #-}
1460mapMaybe :: (IsStream t, Monad m) => (a -> Maybe b) -> t m a -> t m b
1461mapMaybe f m = fromStreamS $ S.mapMaybe f $ toStreamS m
1463-- | Like 'mapMaybe' but maps a monadic function.
1468-- mapMaybeM f = Stream.map 'fromJust' . Stream.filter 'isJust' . Stream.mapM f
1471-- /Concurrent (do not use with 'fromParallel' on infinite streams)/
1474{-# INLINE_EARLY mapMaybeM #-}
1475mapMaybeM :: (IsStream t, MonadAsync m, Functor (t m))
1476 => (a -> m (Maybe b)) -> t m a -> t m b
1477mapMaybeM f = fmap fromJust . filter isJust . K.mapM f
1479{-# RULES "mapMaybeM serial" mapMaybeM = mapMaybeMSerial #-}
1480{-# INLINE mapMaybeMSerial #-}
1481mapMaybeMSerial :: Monad m => (a -> m (Maybe b)) -> SerialT m a -> SerialT m b
1482mapMaybeMSerial f m = fromStreamD $ D.mapMaybeM f $ toStreamD m
1484-- | In a stream of 'Maybe's, discard 'Nothing's and unwrap 'Just's.
1488catMaybes :: (IsStream t, Monad m, Functor (t m)) => t m (Maybe a) -> t m a
1489catMaybes = fmap fromJust . filter isJust
1491------------------------------------------------------------------------------
1493------------------------------------------------------------------------------
1495-- | Discard 'Right's and unwrap 'Left's in an 'Either' stream.
1499lefts :: (IsStream t, Monad m, Functor (t m)) => t m (Either a b) -> t m a
1500lefts = fmap (fromLeft undefined) . filter isLeft
1502-- | Discard 'Left's and unwrap 'Right's in an 'Either' stream.
1506rights :: (IsStream t, Monad m, Functor (t m)) => t m (Either a b) -> t m b
1507rights = fmap (fromRight undefined) . filter isRight
1509------------------------------------------------------------------------------
1510-- Concurrent Application
1511------------------------------------------------------------------------------
1513-- | Parallel transform application operator; applies a stream transformation
1514-- function @t m a -> t m b@ to a stream @t m a@ concurrently; the input stream
1515-- is evaluated asynchronously in an independent thread yielding elements to a
1516-- buffer and the transformation function runs in another thread consuming the
1517-- input from the buffer. '|$' is just like regular function application
1518-- operator '$' except that it is concurrent.
1520-- If you read the signature as @(t m a -> t m b) -> (t m a -> t m b)@ you can
1521-- look at it as a transformation that converts a transform function to a
1522-- buffered concurrent transform function.
1524-- The following code prints a value every second even though each stage adds a
1530-- Stream.mapM (\x -> threadDelay 1000000 >> print x)
1531-- |$ Stream.replicateM 3 (threadDelay 1000000 >> return 1)
1539-- /Since: 0.3.0 ("Streamly")/
1543(|$) :: (IsStream t, MonadAsync m) => (t m a -> t m b) -> (t m a -> t m b)
1544-- (|$) f = f . Async.mkAsync
1545(|$) f = f . Par.mkParallel
1553{-# INLINE applyAsync #-}
1554applyAsync :: (IsStream t, MonadAsync m)
1555 => (t m a -> t m b) -> (t m a -> t m b)
1558-- | Same as '|$' but with arguments reversed.
1564-- /Since: 0.3.0 ("Streamly")/
1568(|&) :: (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