2-- Module : Streamly.Internal.Data.Stream.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.Transform
12 -- | Pass through a 'Pipe'.
19 -- | Stateless one-to-one maps.
23 -- * Mapping Side Effects (Observation)
24 -- | See also the intersperse*_ combinators.
37 -- | Produce a subset of the stream using criteria based on the values of
38 -- the elements. We can use a concatMap and scan for filtering but these
39 -- combinators are more efficient and convenient.
41 -- mapMaybeM is a general filtering combinator as we can map the stream to
42 -- Just/Nothing using any stateful fold and then use this to filter out.
53 -- Stateful/scanning filters
60 -- | Produce a subset of the stream trimmed at ends.
74 -- * Position Indexing
85 , findIndices -- XXX indicesBy
86 , elemIndices -- XXX indicesOf
89 -- | Map using the previous element.
96 -- * Inserting Elements
97 -- | Produce a superset of the stream. This is the opposite of
98 -- filtering/sampling. We can always use concatMap and scan for inserting
99 -- but these combinators are more efficient and convenient.
101 -- Element agnostic (Opposite of sampling)
103 , intersperseM -- XXX naming
107 , intersperseSuffixBySpan
109 -- , interspersePrefix
110 -- , interspersePrefixBySpan
112 -- * Inserting Side Effects/Time
113 , intersperseM_ -- XXX naming
120 -- * Element Aware Insertion
121 -- | Opposite of filtering
123 -- , intersperseByBefore
124 -- , intersperseByAfter
126 -- Fold and Unfold, Buffering
134 -- Move these to Streamly.Data.Either.Stream?
143import Control.Concurrent (threadDelay)
144import Control.Monad (void)
145import Control.Monad.IO.Class (MonadIO (liftIO))
146import Data.Either (fromLeft, isLeft, isRight, fromRight)
147import Data.Maybe (isJust, fromJust)
149import Streamly.Internal.Data.Fold.Type (Fold)
150import Streamly.Internal.Data.Pipe (Pipe)
151import Streamly.Internal.Data.Time.Units (AbsTime, RelTime64)
153import qualified Streamly.Internal.Data.Fold as FL
154-- import qualified Streamly.Internal.Data.Fold.Window as Window
155import qualified Streamly.Internal.Data.Stream.StreamD.Transform as D
156import qualified Streamly.Internal.Data.Stream.StreamD.Type as D
157import qualified Streamly.Internal.Data.Stream.StreamK.Type as K
160import Streamly.Internal.Data.Stream.Bottom
161import Streamly.Internal.Data.Stream.Type
164 ( filter, drop, dropWhile, take, takeWhile, foldr, map, mapM, sequence
165 , reverse, foldr1 , repeat, scanl, scanl1, zipWith)
170-- >>> :set -package mtl
171-- >>> import Control.Concurrent (threadDelay)
172-- >>> import Control.Monad.IO.Class (MonadIO (liftIO))
173-- >>> import Control.Monad.Trans (lift)
174-- >>> import Control.Monad.Trans.Identity (runIdentityT)
175-- >>> import Data.Either (fromLeft, fromRight, isLeft, isRight, either)
176-- >>> import Data.Function ((&))
177-- >>> import Data.Maybe (fromJust, isJust)
178-- >>> import Prelude hiding (filter, drop, dropWhile, take, takeWhile, foldr, map, mapM, sequence, reverse, foldr1 , scanl, scanl1)
179-- >>> import Streamly.Internal.Data.Stream as Stream
180-- >>> import qualified Streamly.Data.Fold as Fold
181-- >>> import qualified Streamly.Internal.Data.Fold as Fold
182-- >>> import qualified Streamly.Internal.Data.Fold.Window as Window
183-- >>> import qualified Streamly.Internal.Data.Unfold as Unfold
184-- >>> import System.IO (stdout, hSetBuffering, BufferMode(LineBuffering))
186-- >>> hSetBuffering stdout LineBuffering
188-- XXX because of the use of D.cons for appending, folds and scans have
189-- quadratic complexity when iterated over a stream. We should use StreamK for
190-- linear performance on iteration.
192------------------------------------------------------------------------------
194------------------------------------------------------------------------------
196-- | Use a 'Pipe' to transform a stream.
200{-# INLINE transform #-}
201transform :: Monad m => Pipe m a b -> Stream m a -> Stream m b
202transform pipe xs = fromStreamD $ D.transform pipe (toStreamD xs)
204------------------------------------------------------------------------------
205-- Transformation Folds
206------------------------------------------------------------------------------
208-- | Right fold to a streaming monad.
210-- > foldrS Stream.cons Stream.nil === id
212-- 'foldrS' can be used to perform stateless stream to stream transformations
213-- like map and filter in general. It can be coupled with a scan to perform
214-- stateful transformations. However, note that the custom map and filter
215-- routines can be much more efficient than this due to better stream fusion.
217-- >>> input = Stream.fromList [1..5]
218-- >>> Stream.fold Fold.toList $ Stream.foldrS Stream.cons Stream.nil input
221-- Find if any element in the stream is 'True':
223-- >>> step x xs = if odd x then return True else xs
224-- >>> input = Stream.fromList (2:4:5:undefined) :: Stream IO Int
225-- >>> Stream.fold Fold.toList $ Stream.foldrS step (return False) input
228-- Map (+2) on odd elements and filter out the even elements:
230-- >>> step x xs = if odd x then (x + 2) `Stream.cons` xs else xs
231-- >>> input = Stream.fromList [1..5] :: Stream IO Int
232-- >>> Stream.fold Fold.toList $ Stream.foldrS step Stream.nil input
238 (a -> Stream m b -> Stream m b)
245 (\y ys -> toStreamK $ f y (fromStreamK ys))
249------------------------------------------------------------------------------
250-- Transformation by Mapping
251------------------------------------------------------------------------------
254-- >>> mapM f = Stream.sequence . fmap f
256-- Apply a monadic function to each element of the stream and replace it with
257-- the output of the resulting action.
259-- >>> s = Stream.fromList ["a", "b", "c"]
260-- >>> Stream.fold Fold.drain $ Stream.mapM putStr s
264mapM :: Monad m => (a -> m b) -> Stream m a -> Stream m b
265mapM f m = fromStreamK $ D.toStreamK $ D.mapM f $ toStreamD m
268-- >>> sequence = Stream.mapM id
270-- Replace the elements of a stream of monadic actions with the outputs of
273-- >>> s = Stream.fromList [putStr "a", putStr "b", putStrLn "c"]
274-- >>> Stream.fold Fold.drain $ Stream.sequence s
277{-# INLINE sequence #-}
278sequence :: Monad m => Stream m (m a) -> Stream m a
281------------------------------------------------------------------------------
282-- Mapping side effects
283------------------------------------------------------------------------------
285-- | Tap the data flowing through a stream into a 'Fold'. For example, you may
286-- add a tap to log the contents flowing through the stream. The fold is used
287-- only for effects, its result is discarded.
292-- -----stream m a ---------------stream m a-----
296-- >>> s = Stream.enumerateFromTo 1 2
297-- >>> Stream.fold Fold.drain $ Stream.tap (Fold.drainMapM print) s
301-- Compare with 'trace'.
304tap :: Monad m => FL.Fold m a b -> Stream m a -> Stream m a
305tap f xs = fromStreamD $ D.tap f (toStreamD xs)
307-- | Apply a monadic function to each element flowing through the stream and
308-- discard the results.
310-- >>> s = Stream.enumerateFromTo 1 2
311-- >>> Stream.fold Fold.drain $ Stream.trace print s
315-- Compare with 'tap'.
318trace :: Monad m => (a -> m b) -> Stream m a -> Stream m a
319trace f = mapM (\x -> void (f x) >> return x)
321-- | Perform a side effect before yielding each element of the stream and
322-- discard the results.
324-- >>> s = Stream.enumerateFromTo 1 2
325-- >>> Stream.fold Fold.drain $ Stream.trace_ (print "got here") s
329-- Same as 'interspersePrefix_' but always serial.
335trace_ :: Monad m => m b -> Stream m a -> Stream m a
336trace_ eff = fromStreamD . D.mapM (\x -> eff >> return x) . toStreamD
338-------------------------------------------------------------------------------
340-------------------------------------------------------------------------------
342-- | @scanlMAfter' accumulate initial done stream@ is like 'scanlM'' except
343-- that it provides an additional @done@ function to be applied on the
344-- accumulator when the stream stops. The result of @done@ is also emitted in
347-- This function can be used to allocate a resource in the beginning of the
348-- scan and release it when the stream ends or to flush the internal state of
349-- the scan at the end.
353{-# INLINE scanlMAfter' #-}
361scanlMAfter' step initial done stream =
362 fromStreamD $ D.scanlMAfter' step initial done $ toStreamD stream
364------------------------------------------------------------------------------
365-- Scanning with a Fold
366------------------------------------------------------------------------------
368-- XXX It may be useful to have a version of scan where we can keep the
369-- accumulator independent of the value emitted. So that we do not necessarily
370-- have to keep a value in the accumulator which we are not using. We can pass
371-- an extraction function that will take the accumulator and the current value
372-- of the element and emit the next value in the stream. That will also make it
373-- possible to modify the accumulator after using it. In fact, the step function
374-- can return new accumulator and the value to be emitted. The signature would
375-- be more like mapAccumL.
377-- | Strict left scan. Scan a stream using the given monadic fold.
379-- >>> s = Stream.fromList [1..10]
380-- >>> Stream.fold Fold.toList $ Stream.takeWhile (< 10) $ Stream.scan Fold.sum s
383-- See also: 'usingStateT'
387-- >>> scanl' step z = Stream.scan (Fold.foldl' step z)
389-- Like 'map', 'scanl'' too is a one to one transformation,
390-- however it adds an extra element.
392-- >>> s = Stream.fromList [1,2,3,4]
393-- >>> Stream.fold Fold.toList $ scanl' (+) 0 s
396-- >>> Stream.fold Fold.toList $ scanl' (flip (:)) [] s
397-- [[],[1],[2,1],[3,2,1],[4,3,2,1]]
399-- The output of 'scanl'' is the initial value of the accumulator followed by
400-- all the intermediate steps and the final result of 'foldl''.
402-- By streaming the accumulated state after each fold step, we can share the
403-- state across multiple stages of stream composition. Each stage can modify or
404-- extend the state, do some processing with it and emit it for the next stage,
405-- thus modularizing the stream processing. This can be useful in
406-- stateful or event-driven programming.
408-- Consider the following monolithic example, computing the sum and the product
409-- of the elements in a stream in one go using a @foldl'@:
411-- >>> foldl' step z = Stream.fold (Fold.foldl' step z)
412-- >>> foldl' (\(s, p) x -> (s + x, p * x)) (0,1) s
415-- Using @scanl'@ we can make it modular by computing the sum in the first
416-- stage and passing it down to the next stage for computing the product:
419-- foldl' (\(_, p) (s, x) -> (s, p * x)) (0,1)
420-- $ scanl' (\(s, _) x -> (s + x, x)) (0,1)
421-- $ Stream.fromList [1,2,3,4]
425-- IMPORTANT: 'scanl'' evaluates the accumulator to WHNF. To avoid building
426-- lazy expressions inside the accumulator, it is recommended that a strict
427-- data structure is used for accumulator.
430scan :: Monad m => Fold m a b -> Stream m a -> Stream m b
431scan fld m = fromStreamD $ D.scanOnce fld $ toStreamD m
433-- | Like 'scan' but restarts scanning afresh when the scanning fold
436{-# INLINE scanMany #-}
437scanMany :: Monad m => Fold m a b -> Stream m a -> Stream m b
438scanMany fld m = fromStreamD $ D.scanMany fld $ toStreamD m
440------------------------------------------------------------------------------
442------------------------------------------------------------------------------
444-- | Modify a @Stream m a -> Stream m a@ stream transformation that accepts a
445-- predicate @(a -> b)@ to accept @((s, a) -> b)@ instead, provided a
446-- transformation @Stream m a -> Stream m (s, a)@. Convenient to filter with
449-- >>> filterWithIndex = Stream.with Stream.indexed Stream.filter
454 (Stream m a -> Stream m (s, a))
455 -> (((s, a) -> b) -> Stream m (s, a) -> Stream m (s, a))
456 -> (((s, a) -> b) -> Stream m a -> Stream m a)
457with f comb g = fmap snd . comb g . f
459-- | Include only those elements that pass a predicate.
461-- >>> filter p = Stream.filterM (return . p)
462-- >>> filter p = Stream.mapMaybe (\x -> if p x then Just x else Nothing)
463-- >>> filter p = Stream.scanMaybe (Fold.filtering p)
466filter :: Monad m => (a -> Bool) -> Stream m a -> Stream m a
467-- filter p = scanMaybe (FL.filtering p)
468filter p m = fromStreamD $ D.filter p $ toStreamD m
470-- | Same as 'filter' but with a monadic predicate.
472-- >>> f p x = p x >>= \r -> return $ if r then Just x else Nothing
473-- >>> filterM p = Stream.mapMaybeM (f p)
475{-# INLINE filterM #-}
476filterM :: Monad m => (a -> m Bool) -> Stream m a -> Stream m a
477filterM p m = fromStreamD $ D.filterM p $ toStreamD m
479-- | Drop repeated elements that are adjacent to each other using the supplied
480-- comparison function.
482-- >>> uniq = Stream.uniqBy (==)
484-- To strip duplicate path separators:
486-- >>> input = Stream.fromList "//a//b"
487-- >>> f x y = x == '/' && y == '/'
488-- >>> Stream.fold Fold.toList $ Stream.uniqBy f input
497 (a -> a -> Bool) -> Stream m a -> Stream m a
498-- uniqBy eq = scanMaybe (FL.uniqBy eq)
499uniqBy eq = catMaybes . rollingMap f
506 Just x -> if x `eq` curr then Nothing else Just curr
508-- | Drop repeated elements that are adjacent to each other.
510-- >>> uniq = Stream.uniqBy (==)
513uniq :: (Eq a, Monad m) => Stream m a -> Stream m a
514-- uniq = scanMaybe FL.uniq
515uniq = fromStreamD . D.uniq . toStreamD
517-- | Strip all leading and trailing occurrences of an element passing a
518-- predicate and make all other consecutive occurrences uniq.
520-- >> prune p = Stream.dropWhileAround p $ Stream.uniqBy (x y -> p x && p y)
523-- > Stream.prune isSpace (Stream.fromList " hello world! ")
533 -- (Monad m, Eq a) =>
534 (a -> Bool) -> Stream m a -> Stream m a
535prune = error "Not implemented yet!"
537-- Possible implementation:
539-- Stream.catMaybes . Stream.parseMany (Parser.groupBy (==) Fold.repeated)@
541-- 'Fold.repeated' should return 'Just' when repeated, and 'Nothing' for a
544-- | Emit only repeated elements, once.
547repeated :: -- (Monad m, Eq a) =>
548 Stream m a -> Stream m a
551-- | Deletes the first occurrence of the element in the stream that satisfies
552-- the given equality predicate.
554-- >>> input = Stream.fromList [1,3,3,5]
555-- >>> Stream.fold Fold.toList $ Stream.deleteBy (==) 3 input
558{-# INLINE deleteBy #-}
559deleteBy :: Monad m => (a -> a -> Bool) -> a -> Stream m a -> Stream m a
560-- deleteBy cmp x = scanMaybe (FL.deleteBy cmp x)
561deleteBy cmp x m = fromStreamD $ D.deleteBy cmp x (toStreamD m)
563------------------------------------------------------------------------------
565------------------------------------------------------------------------------
567-- | Same as 'takeWhile' but with a monadic predicate.
569{-# INLINE takeWhileM #-}
570takeWhileM :: Monad m => (a -> m Bool) -> Stream m a -> Stream m a
571-- takeWhileM p = scanMaybe (FL.takingEndByM_ (\x -> not <$> p x))
572takeWhileM p m = fromStreamD $ D.takeWhileM p $ toStreamD m
574-- | Take all consecutive elements at the end of the stream for which the
577-- O(n) space, where n is the number elements taken.
580{-# INLINE takeWhileLast #-}
581takeWhileLast :: -- Monad m =>
582 (a -> Bool) -> Stream m a -> Stream m a
583takeWhileLast = undefined -- fromStreamD $ D.takeWhileLast n $ toStreamD m
585-- | Like 'takeWhile' and 'takeWhileLast' combined.
587-- O(n) space, where n is the number elements taken from the end.
590{-# INLINE takeWhileAround #-}
591takeWhileAround :: -- Monad m =>
592 (a -> Bool) -> Stream m a -> Stream m a
593takeWhileAround = undefined -- fromStreamD $ D.takeWhileAround n $ toStreamD m
595-- | Drop elements in the stream as long as the predicate succeeds and then
596-- take the rest of the stream.
598{-# INLINE dropWhile #-}
599dropWhile :: Monad m => (a -> Bool) -> Stream m a -> Stream m a
600-- dropWhile p = scanMaybe (FL.droppingWhile p)
601dropWhile p m = fromStreamD $ D.dropWhile p $ toStreamD m
603-- | Same as 'dropWhile' but with a monadic predicate.
605{-# INLINE dropWhileM #-}
606dropWhileM :: Monad m => (a -> m Bool) -> Stream m a -> Stream m a
607-- dropWhileM p = scanMaybe (FL.droppingWhileM p)
608dropWhileM p m = fromStreamD $ D.dropWhileM p $ toStreamD m
610-- | Drop @n@ elements at the end of the stream.
612-- O(n) space, where n is the number elements dropped.
615{-# INLINE dropLast #-}
616dropLast :: -- Monad m =>
617 Int -> Stream m a -> Stream m a
618dropLast = undefined -- fromStreamD $ D.dropLast n $ toStreamD m
620-- | Drop all consecutive elements at the end of the stream for which the
623-- O(n) space, where n is the number elements dropped.
626{-# INLINE dropWhileLast #-}
627dropWhileLast :: -- Monad m =>
628 (a -> Bool) -> Stream m a -> Stream m a
629dropWhileLast = undefined -- fromStreamD $ D.dropWhileLast n $ toStreamD m
631-- | Like 'dropWhile' and 'dropWhileLast' combined.
633-- O(n) space, where n is the number elements dropped from the end.
636{-# INLINE dropWhileAround #-}
637dropWhileAround :: -- Monad m =>
638 (a -> Bool) -> Stream m a -> Stream m a
639dropWhileAround = undefined -- fromStreamD $ D.dropWhileAround n $ toStreamD m
641------------------------------------------------------------------------------
643------------------------------------------------------------------------------
645-- | @insertBy cmp elem stream@ inserts @elem@ before the first element in
646-- @stream@ that is less than @elem@ when compared using @cmp@.
648-- >>> insertBy cmp x = Stream.mergeBy cmp (Stream.fromPure x)
650-- >>> input = Stream.fromList [1,3,5]
651-- >>> Stream.fold Fold.toList $ Stream.insertBy compare 2 input
654{-# INLINE insertBy #-}
655insertBy ::Monad m => (a -> a -> Ordering) -> a -> Stream m a -> Stream m a
656insertBy cmp x m = fromStreamD $ D.insertBy cmp x (toStreamD m)
658-- | Insert a pure value between successive elements of a stream.
660-- >>> input = Stream.fromList "hello"
661-- >>> Stream.fold Fold.toList $ Stream.intersperse ',' input
664{-# INLINE intersperse #-}
665intersperse :: Monad m => a -> Stream m a -> Stream m a
666intersperse a = fromStreamD . D.intersperse a . toStreamD
668-- | Insert a side effect before consuming an element of a stream except the
671-- >>> input = Stream.fromList "hello"
672-- >>> Stream.fold Fold.drain $ Stream.trace putChar $ Stream.intersperseM_ (putChar '.') input
676{-# INLINE intersperseM_ #-}
677intersperseM_ :: Monad m => m b -> Stream m a -> Stream m a
678intersperseM_ m = fromStreamD . D.intersperseM_ m . toStreamD
680-- | Intersperse a monadic action into the input stream after every @n@
683-- >> input = Stream.fromList "hello"
684-- >> Stream.fold Fold.toList $ Stream.intersperseBySpan 2 (return ',') input
688{-# INLINE intersperseBySpan #-}
689intersperseBySpan :: -- Monad m =>
690 Int -> m a -> Stream m a -> Stream m a
691intersperseBySpan _n _f _xs = undefined
693-- | Insert an effect and its output after consuming an element of a stream.
695-- >>> input = Stream.fromList "hello"
696-- >>> Stream.fold Fold.toList $ Stream.trace putChar $ intersperseSuffix (putChar '.' >> return ',') input
697-- h.,e.,l.,l.,o.,"h,e,l,l,o,"
700{-# INLINE intersperseSuffix #-}
701intersperseSuffix :: Monad m => m a -> Stream m a -> Stream m a
702intersperseSuffix m = fromStreamD . D.intersperseSuffix m . toStreamD
704-- | Insert a side effect after consuming an element of a stream.
706-- >>> input = Stream.fromList "hello"
707-- >>> Stream.fold Fold.toList $ Stream.intersperseSuffix_ (threadDelay 1000000) input
712{-# INLINE intersperseSuffix_ #-}
713intersperseSuffix_ :: Monad m => m b -> Stream m a -> Stream m a
714intersperseSuffix_ m = fromStreamD . D.intersperseSuffix_ m . toStreamD
716-- XXX Use an offset argument, like tapOffsetEvery
718-- | Like 'intersperseSuffix' but intersperses an effectful action into the
719-- input stream after every @n@ elements and after the last element.
721-- >>> input = Stream.fromList "hello"
722-- >>> Stream.fold Fold.toList $ Stream.intersperseSuffixBySpan 2 (return ',') input
727{-# INLINE intersperseSuffixBySpan #-}
728intersperseSuffixBySpan :: Monad m
729 => Int -> m a -> Stream m a -> Stream m a
730intersperseSuffixBySpan n eff =
731 fromStreamD . D.intersperseSuffixBySpan n eff . toStreamD
733-- | Insert a side effect before consuming an element of a stream.
735-- >>> input = Stream.fromList "hello"
736-- >>> Stream.fold Fold.toList $ Stream.trace putChar $ Stream.interspersePrefix_ (putChar '.' >> return ',') input
743{-# INLINE interspersePrefix_ #-}
744interspersePrefix_ :: Monad m => m b -> Stream m a -> Stream m a
745interspersePrefix_ m = mapM (\x -> void m >> return x)
747------------------------------------------------------------------------------
749------------------------------------------------------------------------------
751-- | Introduce a delay of specified seconds between elements of the stream.
753-- >>> input = Stream.enumerateFromTo 1 3
754-- >>> Stream.fold (Fold.drainMapM print) $ Stream.delay 1 input
759-- >>> sleep n = liftIO $ threadDelay $ round $ n * 1000000
760-- >>> delay n = Stream.intersperseM_ $ sleep n
763delay :: MonadIO m => Double -> Stream m a -> Stream m a
764delay n = intersperseM_ $ liftIO $ threadDelay $ round $ n * 1000000
766-- | Introduce a delay of specified seconds after consuming an element of a
769-- >>> input = Stream.enumerateFromTo 1 3
770-- >>> Stream.fold (Fold.drainMapM print) $ Stream.delayPost 1 input
777{-# INLINE delayPost #-}
778delayPost :: MonadIO m => Double -> Stream m a -> Stream m a
779delayPost n = intersperseSuffix_ $ liftIO $ threadDelay $ round $ n * 1000000
781-- | Introduce a delay of specified seconds before consuming an element of a
784-- >>> input = Stream.enumerateFromTo 1 3
785-- >>> Stream.fold (Fold.drainMapM print) $ Stream.delayPre 1 input
792{-# INLINE delayPre #-}
793delayPre :: MonadIO m => Double -> Stream m a -> Stream m a
794delayPre n = trace_ $ liftIO $ threadDelay $ round $ n * 1000000
796------------------------------------------------------------------------------
797-- Reorder in sequence
798------------------------------------------------------------------------------
800-- | Buffer until the next element in sequence arrives. The function argument
801-- determines the difference in sequence numbers. This could be useful in
802-- implementing sequenced streams, for example, TCP reassembly.
806{-# INLINE reassembleBy #-}
813reassembleBy = undefined
815------------------------------------------------------------------------------
817------------------------------------------------------------------------------
820-- >>> f = Fold.foldl' (\(i, _) x -> (i + 1, x)) (-1,undefined)
821-- >>> indexed = Stream.postscan f
822-- >>> indexed = Stream.zipWith (,) (Stream.enumerateFrom 0)
823-- >>> indexedR n = fmap (\(i, a) -> (n - i, a)) . indexed
825-- Pair each element in a stream with its index, starting from index 0.
827-- >>> Stream.fold Fold.toList $ Stream.indexed $ Stream.fromList "hello"
828-- [(0,'h'),(1,'e'),(2,'l'),(3,'l'),(4,'o')]
830{-# INLINE indexed #-}
831indexed :: Monad m => Stream m a -> Stream m (Int, a)
832-- indexed = scanMaybe FL.indexing
833indexed = fromStreamD . D.indexed . toStreamD
836-- >>> f n = Fold.foldl' (\(i, _) x -> (i - 1, x)) (n + 1,undefined)
837-- >>> indexedR n = Stream.postscan (f n)
839-- >>> s n = Stream.enumerateFromThen n (n - 1)
840-- >>> indexedR n = Stream.zipWith (,) (s n)
842-- Pair each element in a stream with its index, starting from the
843-- given index @n@ and counting down.
845-- >>> Stream.fold Fold.toList $ Stream.indexedR 10 $ Stream.fromList "hello"
846-- [(10,'h'),(9,'e'),(8,'l'),(7,'l'),(6,'o')]
848{-# INLINE indexedR #-}
849indexedR :: Monad m => Int -> Stream m a -> Stream m (Int, a)
850-- indexedR n = scanMaybe (FL.indexingRev n)
851indexedR n = fromStreamD . D.indexedR n . toStreamD
853-------------------------------------------------------------------------------
855-------------------------------------------------------------------------------
857-- Note: The timestamp stream must be the second stream in the zip so that the
858-- timestamp is generated after generating the stream element and not before.
859-- If we do not do that then the following example will generate the same
860-- timestamp for first two elements:
862-- Stream.fold Fold.toList $ Stream.timestamped $ Stream.delay $ Stream.enumerateFromTo 1 3
864-- | Pair each element in a stream with an absolute timestamp, using a clock of
865-- specified granularity. The timestamp is generated just before the element
868-- >>> Stream.fold Fold.toList $ Stream.timestampWith 0.01 $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
869-- [(AbsTime (TimeSpec {sec = ..., nsec = ...}),1),(AbsTime (TimeSpec {sec = ..., nsec = ...}),2),(AbsTime (TimeSpec {sec = ..., nsec = ...}),3)]
873{-# INLINE timestampWith #-}
874timestampWith :: (MonadIO m)
875 => Double -> Stream m a -> Stream m (AbsTime, a)
876timestampWith g stream = zipWith (flip (,)) stream (absTimesWith g)
878-- TBD: check performance vs a custom implementation without using zipWith.
882{-# INLINE timestamped #-}
883timestamped :: (MonadIO m)
884 => Stream m a -> Stream m (AbsTime, a)
885timestamped = timestampWith 0.01
887-- | Pair each element in a stream with relative times starting from 0, using a
888-- clock with the specified granularity. The time is measured just before the
889-- element is consumed.
891-- >>> Stream.fold Fold.toList $ Stream.timeIndexWith 0.01 $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
892-- [(RelTime64 (NanoSecond64 ...),1),(RelTime64 (NanoSecond64 ...),2),(RelTime64 (NanoSecond64 ...),3)]
896{-# INLINE timeIndexWith #-}
897timeIndexWith :: (MonadIO m)
898 => Double -> Stream m a -> Stream m (RelTime64, a)
899timeIndexWith g stream = zipWith (flip (,)) stream (relTimesWith g)
901-- | Pair each element in a stream with relative times starting from 0, using a
902-- 10 ms granularity clock. The time is measured just before the element is
905-- >>> Stream.fold Fold.toList $ Stream.timeIndexed $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
906-- [(RelTime64 (NanoSecond64 ...),1),(RelTime64 (NanoSecond64 ...),2),(RelTime64 (NanoSecond64 ...),3)]
910{-# INLINE timeIndexed #-}
911timeIndexed :: (MonadIO m)
912 => Stream m a -> Stream m (RelTime64, a)
913timeIndexed = timeIndexWith 0.01
915------------------------------------------------------------------------------
917------------------------------------------------------------------------------
919-- | Find all the indices where the value of the element in the stream is equal
920-- to the given value.
922-- >>> elemIndices a = Stream.findIndices (== a)
924{-# INLINE elemIndices #-}
925elemIndices :: (Monad m, Eq a) => a -> Stream m a -> Stream m Int
926elemIndices a = findIndices (== a)
928------------------------------------------------------------------------------
930------------------------------------------------------------------------------
932-- XXX this is not a one-to-one map so calling it map may not be right.
933-- We can perhaps call it zipWithTail or rollWith.
935-- | Apply a function on every two successive elements of a stream. The first
936-- argument of the map function is the previous element and the second argument
937-- is the current element. When the current element is the first element, the
938-- previous element is 'Nothing'.
942{-# INLINE rollingMap #-}
943rollingMap :: Monad m => (Maybe a -> a -> b) -> Stream m a -> Stream m b
944-- rollingMap f = scanMaybe (FL.slide2 $ Window.rollingMap f)
945rollingMap f m = fromStreamD $ D.rollingMap f $ toStreamD m
947-- | Like 'rollingMap' but with an effectful map function.
951{-# INLINE rollingMapM #-}
952rollingMapM :: Monad m => (Maybe a -> a -> m b) -> Stream m a -> Stream m b
953-- rollingMapM f = scanMaybe (FL.slide2 $ Window.rollingMapM f)
954rollingMapM f m = fromStreamD $ D.rollingMapM f $ toStreamD m
956-- | Like 'rollingMap' but requires at least two elements in the stream,
957-- returns an empty stream otherwise.
959-- This is the stream equivalent of the list idiom @zipWith f xs (tail xs)@.
963{-# INLINE rollingMap2 #-}
964rollingMap2 :: Monad m => (a -> a -> b) -> Stream m a -> Stream m b
965rollingMap2 f m = fromStreamD $ D.rollingMap2 f $ toStreamD m
967------------------------------------------------------------------------------
969------------------------------------------------------------------------------
971-- | Map a 'Maybe' returning function to a stream, filter out the 'Nothing'
972-- elements, and return a stream of values extracted from 'Just'.
976-- >>> mapMaybe f = Stream.catMaybes . fmap f
978{-# INLINE mapMaybe #-}
979mapMaybe :: Monad m => (a -> Maybe b) -> Stream m a -> Stream m b
980mapMaybe f m = fromStreamD $ D.mapMaybe f $ toStreamD m
982-- | Like 'mapMaybe' but maps a monadic function.
986-- >>> mapMaybeM f = Stream.catMaybes . Stream.mapM f
988-- >>> mapM f = Stream.mapMaybeM (\x -> Just <$> f x)
990{-# INLINE_EARLY mapMaybeM #-}
992 => (a -> m (Maybe b)) -> Stream m a -> Stream m b
993mapMaybeM f = fmap fromJust . filter isJust . mapM f
995------------------------------------------------------------------------------
997------------------------------------------------------------------------------
999-- | Discard 'Right's and unwrap 'Left's in an 'Either' stream.
1001-- >>> lefts = fmap (fromLeft undefined) . Stream.filter isLeft
1006lefts :: Monad m => Stream m (Either a b) -> Stream m a
1007lefts = fmap (fromLeft undefined) . filter isLeft
1009-- | Discard 'Left's and unwrap 'Right's in an 'Either' stream.
1011-- >>> rights = fmap (fromRight undefined) . Stream.filter isRight
1015{-# INLINE rights #-}
1016rights :: Monad m => Stream m (Either a b) -> Stream m b
1017rights = fmap (fromRight undefined) . filter isRight
1019-- | Remove the either wrapper and flatten both lefts and as well as rights in
1020-- the output stream.
1022-- >>> both = fmap (either id id)
1027both :: Monad m => Stream m (Either a a) -> Stream m a
1028both = fmap (either id id)
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