1{-# OPTIONS_GHC -Wno-orphans #-}
4-- Module : Streamly.Internal.Data.Stream.IsStream.Common
5-- Copyright : (c) 2017 Composewell Technologies
6-- License : BSD-3-Clause
7-- Maintainer : streamly@composewell.com
8-- Stability : experimental
11-- Bottom level IsStream module that can be used by all other upper level
14module Streamly.Internal.Data.Stream.IsStream.Common
70import Control.Concurrent (threadDelay)
71import Control.Monad.IO.Class (MonadIO(..))
72import Streamly.Internal.Control.Concurrent (MonadAsync)
73import Streamly.Internal.Data.Array.Unboxed.Type (Array)
74import Streamly.Internal.Data.Fold.Type (Fold (..))
75import Streamly.Internal.Data.Stream.IsStream.Combinators (maxYields)
76import Streamly.Internal.Data.Stream.IsStream.Type
77 (IsStream(..), fromStreamD, toStreamD)
78import Streamly.Internal.Data.Stream.Serial (SerialT)
79import Streamly.Internal.Data.Time.Units (AbsTime, RelTime64, addToAbsTime64)
80import Streamly.Internal.System.IO (defaultChunkSize)
81import Streamly.Internal.Data.Unboxed (Unboxed)
83import qualified Streamly.Data.Stream as Stream (fold, foldBreak)
84import qualified Streamly.Internal.Data.Array.Unboxed.Type as A
85import qualified Streamly.Internal.Data.Stream.IsStream.Async as Async
86import qualified Streamly.Internal.Data.Stream.IsStream.Type as IsStream
87import qualified Streamly.Internal.Data.Stream.IsStream.Parallel as Par
88import qualified Streamly.Internal.Data.Stream.StreamK.Type as K
89 (fromPure, fromEffect, repeatMWith, reverse)
90import qualified Streamly.Internal.Data.Stream.StreamD as D
91 (repeatM, times, foldContinue, map, scanlMAfter', postscanlMAfter'
92 , postscanlM', take, takeWhile, takeEndBy, drop, findIndices
93 , fromStreamK, toStreamK, concatMapM, concatMap, foldManyPost, splitOnSeq
94 , zipWithM, zipWith, intersperseM, reverse)
96import Prelude hiding (take, takeWhile, drop, reverse, concatMap, map, zipWith)
101-- >>> import Control.Concurrent (threadDelay)
102-- >>> import Control.Monad (join)
103-- >>> import Control.Monad.Trans.Class (lift)
104-- >>> import Data.Function (fix, (&))
105-- >>> import Data.Semigroup (cycle1)
106-- >>> import Prelude hiding (take, takeWhile, drop, reverse)
107-- >>> import System.IO.Unsafe (unsafePerformIO)
108-- >>> import qualified Streamly.Prelude as Stream
109-- >>> import Streamly.Internal.Data.Stream.IsStream as Stream
110-- >>> import qualified Streamly.Data.Array.Unboxed as Array
111-- >>> import qualified Streamly.Data.Fold as Fold
112-- >>> import qualified Streamly.Internal.Data.Fold as Fold
113-- >>> import qualified Streamly.Data.Unfold as Unfold
115------------------------------------------------------------------------------
117------------------------------------------------------------------------------
119-- Faster than fromEffect because there is no bind.
123-- fromPure a = a \`cons` nil
126-- Create a singleton stream from a pure value.
128-- The following holds in monadic streams, but not in Zip streams:
132-- fromPure = fromEffect . pure
135-- In Zip applicative streams 'fromPure' is not the same as 'pure' because in that
136-- case 'pure' is equivalent to 'repeat' instead. 'fromPure' and 'pure' are
137-- equally efficient, in other cases 'fromPure' may be slightly more efficient
138-- than the other equivalent definitions.
140-- /Since: 0.8.0 (Renamed yield to fromPure)/
142{-# INLINE fromPure #-}
143fromPure :: IsStream t => a -> t m a
144fromPure = fromStream . K.fromPure
146-- | Same as 'fromPure'
149{-# DEPRECATED yield "Please use fromPure instead." #-}
151yield :: IsStream t => a -> t m a
156-- fromEffect m = m \`consM` nil
159-- Create a singleton stream from a monadic action.
162-- > Stream.toList $ Stream.fromEffect getLine
167-- /Since: 0.8.0 (Renamed yieldM to fromEffect)/
169{-# INLINE fromEffect #-}
170fromEffect :: (Monad m, IsStream t) => m a -> t m a
171fromEffect = fromStream . K.fromEffect
173-- | Same as 'fromEffect'
176{-# DEPRECATED yieldM "Please use fromEffect instead." #-}
178yieldM :: (Monad m, IsStream t) => m a -> t m a
181-- >>> repeatM = fix . consM
182-- >>> repeatM = cycle1 . fromEffect
184-- Generate a stream by repeatedly executing a monadic action forever.
188-- Stream.repeatM (threadDelay 1000000 >> print 1)
194-- /Concurrent, infinite (do not use with 'fromParallel')/
197{-# INLINE_EARLY repeatM #-}
198repeatM :: (IsStream t, MonadAsync m) => m a -> t m a
199repeatM = K.repeatMWith IsStream.consM
201{-# RULES "repeatM serial" repeatM = repeatMSerial #-}
202{-# INLINE repeatMSerial #-}
203repeatMSerial :: MonadAsync m => m a -> SerialT m a
204repeatMSerial = fromStreamD . D.repeatM
206------------------------------------------------------------------------------
207-- Generation - Time related
208------------------------------------------------------------------------------
210-- | @timesWith g@ returns a stream of time value tuples. The first component
211-- of the tuple is an absolute time reference (epoch) denoting the start of the
212-- stream and the second component is a time relative to the reference.
214-- The argument @g@ specifies the granularity of the relative time in seconds.
215-- A lower granularity clock gives higher precision but is more expensive in
216-- terms of CPU usage. Any granularity lower than 1 ms is treated as 1 ms.
218-- >>> import Control.Concurrent (threadDelay)
219-- >>> import Streamly.Internal.Data.Stream.IsStream.Common as Stream (timesWith)
220-- >>> Stream.mapM_ (\x -> print x >> threadDelay 1000000) $ Stream.take 3 $ Stream.timesWith 0.01
221-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),RelTime64 (NanoSecond64 ...))
222-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),RelTime64 (NanoSecond64 ...))
223-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),RelTime64 (NanoSecond64 ...))
225-- Note: This API is not safe on 32-bit machines.
229{-# INLINE timesWith #-}
230timesWith :: (IsStream t, MonadAsync m) => Double -> t m (AbsTime, RelTime64)
231timesWith g = fromStreamD $ D.times g
233-- | @absTimesWith g@ returns a stream of absolute timestamps using a clock of
234-- granularity @g@ specified in seconds. A low granularity clock is more
235-- expensive in terms of CPU usage. Any granularity lower than 1 ms is treated
238-- >>> Stream.mapM_ print $ Stream.delayPre 1 $ Stream.take 3 $ absTimesWith 0.01
239-- AbsTime (TimeSpec {sec = ..., nsec = ...})
240-- AbsTime (TimeSpec {sec = ..., nsec = ...})
241-- AbsTime (TimeSpec {sec = ..., nsec = ...})
243-- Note: This API is not safe on 32-bit machines.
247{-# INLINE absTimesWith #-}
248absTimesWith :: (IsStream t, MonadAsync m, Functor (t m))
249 => Double -> t m AbsTime
250absTimesWith = fmap (uncurry addToAbsTime64) . timesWith
252-- | @relTimesWith g@ returns a stream of relative time values starting from 0,
253-- using a clock of granularity @g@ specified in seconds. A low granularity
254-- clock is more expensive in terms of CPU usage. Any granularity lower than 1
255-- ms is treated as 1 ms.
257-- >>> Stream.mapM_ print $ Stream.delayPre 1 $ Stream.take 3 $ Stream.relTimesWith 0.01
258-- RelTime64 (NanoSecond64 ...)
259-- RelTime64 (NanoSecond64 ...)
260-- RelTime64 (NanoSecond64 ...)
262-- Note: This API is not safe on 32-bit machines.
266{-# INLINE relTimesWith #-}
267relTimesWith :: (IsStream t, MonadAsync m, Functor (t m))
268 => Double -> t m RelTime64
269relTimesWith = fmap snd . timesWith
271------------------------------------------------------------------------------
272-- Elimination - Running a Fold
273------------------------------------------------------------------------------
275-- | We can create higher order folds using 'foldContinue'. We can fold a
276-- number of streams to a given fold efficiently with full stream fusion. For
277-- example, to fold a list of streams on the same sum fold:
279-- >>> concatFold = Prelude.foldl Stream.foldContinue Fold.sum
281-- >>> fold f = Fold.finish . Stream.foldContinue f
284{-# INLINE foldContinue #-}
285foldContinue :: Monad m => Fold m a b -> SerialT m a -> Fold m a b
286foldContinue f s = D.foldContinue f $ IsStream.toStreamD s
288------------------------------------------------------------------------------
290------------------------------------------------------------------------------
300-- > D.toList $ D.map (+1) $ D.fromList [1,2,3]
306map :: (IsStream t, Monad m) => (a -> b) -> t m a -> t m b
307map f = fromStreamD . D.map f . toStreamD
309-- | @scanlMAfter' accumulate initial done stream@ is like 'scanlM'' except
310-- that it provides an additional @done@ function to be applied on the
311-- accumulator when the stream stops. The result of @done@ is also emitted in
314-- This function can be used to allocate a resource in the beginning of the
315-- scan and release it when the stream ends or to flush the internal state of
316-- the scan at the end.
320{-# INLINE scanlMAfter' #-}
321scanlMAfter' :: (IsStream t, Monad m)
322 => (b -> a -> m b) -> m b -> (b -> m b) -> t m a -> t m b
323scanlMAfter' step initial done stream =
324 fromStreamD $ D.scanlMAfter' step initial done $ toStreamD stream
326{-# INLINE postscanlMAfter' #-}
327postscanlMAfter' :: (IsStream t, Monad m)
328 => (b -> a -> m b) -> m b -> (b -> m b) -> t m a -> t m b
329postscanlMAfter' step initial done stream =
330 fromStreamD $ D.postscanlMAfter' step initial done $ toStreamD stream
332-- XXX this needs to be concurrent
333-- | Like 'postscanl'' but with a monadic step function and a monadic seed.
335-- >>> postscanlM' f z xs = Stream.drop 1 $ Stream.scanlM' f z xs
339-- /Since: 0.8.0 (signature change)/
340{-# INLINE postscanlM' #-}
341postscanlM' :: (IsStream t, Monad m) => (b -> a -> m b) -> m b -> t m a -> t m b
342postscanlM' step z m = fromStreamD $ D.postscanlM' step z $ toStreamD m
346-- The stateful step function can be simplified to @(s -> a -> m b)@ to provide
347-- a read-only environment. However, that would just be 'mapM'.
349-- The initial action could be @m (s, Maybe b)@, and we can also add a final
350-- action @s -> m (Maybe b)@. This can be used to get pre/post scan like
351-- functionality and also to flush the state in the end like scanlMAfter'.
352-- We can also use it along with a fusible version of bracket to get
353-- scanlMAfter' like functionality. See issue #677.
355-- This can be further generalized to a type similar to Fold/Parser, giving it
356-- filtering and parsing capability as well (this is in fact equivalent to
359-- smapM :: (s -> a -> m (Step s b)) -> m s -> t m a -> t m b
362-- | A stateful 'mapM', equivalent to a left scan, more like mapAccumL.
363-- Hopefully, this is a better alternative to @scan@. Separation of state from
364-- the output makes it easier to think in terms of a shared state, and also
365-- makes it easier to keep the state fully strict and the output lazy.
367-- See also: 'scanlM''
372smapM :: (IsStream t, Monad m) =>
377smapM step initial stream =
378 -- XXX implement this directly instead of using scanlM'
379 -- Once we have postscanlM' with monadic initial we can use this code
380 -- let r = postscanlM'
381 -- (\(s, _) a -> step s a)
382 -- (fmap (,undefined) initial)
385 (\(s, _) a -> step s a)
386 (fmap (,undefined) initial)
390------------------------------------------------------------------------------
391-- Transformation - Trimming
392------------------------------------------------------------------------------
394-- | Take first 'n' elements from the stream and discard the rest.
398take :: (IsStream t, Monad m) => Int -> t m a -> t m a
399take n m = fromStreamD $ D.take n $ toStreamD
400 (maxYields (Just (fromIntegral n)) m)
402-- | End the stream as soon as the predicate fails on an element.
405{-# INLINE takeWhile #-}
406takeWhile :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m a
407takeWhile p m = fromStreamD $ D.takeWhile p $ toStreamD m
409{-# INLINE takeEndBy #-}
410takeEndBy :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m a
411takeEndBy p m = fromStreamD $ D.takeEndBy p $ toStreamD m
413-- | Discard first 'n' elements from the stream and take the rest.
417drop :: (IsStream t, Monad m) => Int -> t m a -> t m a
418drop n m = fromStreamD $ D.drop n $ toStreamD m
420------------------------------------------------------------------------------
422------------------------------------------------------------------------------
424-- | Find all the indices where the element in the stream satisfies the given
427-- > findIndices = fold Fold.findIndices
430{-# INLINE findIndices #-}
431findIndices :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m Int
432findIndices p m = fromStreamD $ D.findIndices p (toStreamD m)
434------------------------------------------------------------------------------
435-- Transformation by Inserting
436------------------------------------------------------------------------------
438-- intersperseM = intersperseBySpan 1
440-- | Insert an effect and its output before consuming an element of a stream
441-- except the first one.
443-- >>> Stream.toList $ Stream.trace putChar $ Stream.intersperseM (putChar '.' >> return ',') $ Stream.fromList "hello"
444-- h.,e.,l.,l.,o"h,e,l,l,o"
446-- Be careful about the order of effects. In the above example we used trace
447-- after the intersperse, if we use it before the intersperse the output would
448-- be he.l.l.o."h,e,l,l,o".
450-- >>> Stream.toList $ Stream.intersperseM (putChar '.' >> return ',') $ Stream.trace putChar $ Stream.fromList "hello"
451-- he.l.l.o."h,e,l,l,o"
454{-# INLINE intersperseM #-}
455intersperseM :: (IsStream t, MonadAsync m) => m a -> t m a -> t m a
456intersperseM m = fromStreamD . D.intersperseM m . toStreamD
458-- | Intersperse a monadic action into the input stream after every @n@
462-- > import Control.Concurrent (threadDelay)
463-- > Stream.drain $ Stream.interjectSuffix 1 (putChar ',') $ Stream.mapM (\x -> threadDelay 1000000 >> putChar x) $ Stream.fromList "hello"
468{-# INLINE interjectSuffix #-}
470 :: (IsStream t, MonadAsync m)
471 => Double -> m a -> t m a -> t m a
472interjectSuffix n f xs = xs `parallelFst` repeatM timed
473 where timed = liftIO (threadDelay (round $ n * 1000000)) >> f
475------------------------------------------------------------------------------
476-- Transformation by Reordering
477------------------------------------------------------------------------------
479-- XXX Use a compact region list to temporarily store the list, in both reverse
480-- as well as in reverse'.
482-- /Note:/ 'reverse'' is much faster than this, use that when performance
485-- | Returns the elements of the stream in reverse order. The stream must be
486-- finite. Note that this necessarily buffers the entire stream in memory.
488-- >>> reverse = Stream.foldlT (flip Stream.cons) Stream.nil
490-- /Since 0.7.0 (Monad m constraint)/
493{-# INLINE reverse #-}
494reverse :: (IsStream t, Monad m) => t m a -> t m a
495reverse s = fromStreamD $ D.reverse $ toStreamD s
497-- | Like 'reverse' but several times faster, requires a 'Storable' instance.
500{-# INLINE reverse' #-}
501reverse' :: (IsStream t, MonadIO m, Unboxed a) => t m a -> t m a
502-- reverse' s = fromStreamD $ D.reverse' $ toStreamD s
505 . A.flattenArraysRev -- unfoldMany A.readRev
509 . A.arraysOf defaultChunkSize
512------------------------------------------------------------------------------
513-- Concurrent Transformations and Combining
514------------------------------------------------------------------------------
516-- | Make the stream producer and consumer run concurrently by introducing a
517-- buffer between them. The producer thread evaluates the input stream until
518-- the buffer fills, it terminates if the buffer is full and a worker thread is
519-- kicked off again to evaluate the remaining stream when there is space in the
520-- buffer. The consumer consumes the stream lazily from the buffer.
522-- /Since: 0.2.0 (Streamly)/
526{-# INLINE_NORMAL mkAsync #-}
527mkAsync :: (IsStream t, MonadAsync m) => t m a -> t m a
528mkAsync = fromStreamD . Async.mkAsyncD . toStreamD
530-- Compare with mkAsync. mkAsync uses an Async style SVar whereas this uses a
531-- parallel style SVar for evaluation. Currently, parallel style cannot use
532-- rate control whereas Async style can use rate control. In async style SVar
533-- the worker thread terminates when the buffer is full whereas in Parallel
536-- | Make the stream producer and consumer run concurrently by introducing a
537-- buffer between them. The producer thread evaluates the input stream until
538-- the buffer fills, it blocks if the buffer is full until there is space in
539-- the buffer. The consumer consumes the stream lazily from the buffer.
541-- @mkParallel = IsStream.fromStreamD . mkParallelD . IsStream.toStreamD@
545{-# INLINE_NORMAL mkParallel #-}
546mkParallel :: (IsStream t, MonadAsync m) => t m a -> t m a
547mkParallel = fromStreamD . Par.mkParallelD . toStreamD
549-- | Like `parallel` but stops the output as soon as the first stream stops.
552{-# INLINE parallelFst #-}
553parallelFst :: (IsStream t, MonadAsync m) => t m a -> t m a -> t m a
554parallelFst m1 m2 = fromStream $ Par.parallelFstK (toStream m1) (toStream m2)
556------------------------------------------------------------------------------
557-- Combine streams and flatten
558------------------------------------------------------------------------------
560-- | Map a stream producing monadic function on each element of the stream
561-- and then flatten the results into a single stream. Since the stream
562-- generation function is monadic, unlike 'concatMap', it can produce an
563-- effect at the beginning of each iteration of the inner loop.
566{-# INLINE concatMapM #-}
567concatMapM :: (IsStream t, Monad m) => (a -> m (t m b)) -> t m a -> t m b
568concatMapM f m = fromStreamD $ D.concatMapM (fmap toStreamD . f) (toStreamD m)
570-- | Map a stream producing function on each element of the stream and then
571-- flatten the results into a single stream.
573-- >>> concatMap f = Stream.concatMapM (return . f)
574-- >>> concatMap f = Stream.concatMapWith Stream.serial f
575-- >>> concatMap f = Stream.concat . Stream.map f
578{-# INLINE concatMap #-}
579concatMap ::(IsStream t, Monad m) => (a -> t m b) -> t m a -> t m b
580concatMap f m = fromStreamD $ D.concatMap (toStreamD . f) (toStreamD m)
582-- | Given a stream value in the underlying monad, lift and join the underlying
583-- monad with the stream monad.
585-- >>> concatM = Stream.concat . Stream.fromEffect
586-- >>> concatM = Stream.concat . lift -- requires (MonadTrans t)
587-- >>> concatM = join . lift -- requires (MonadTrans t, Monad (t m))
589-- See also: 'concat', 'sequence'
593{-# INLINE concatM #-}
594concatM :: (IsStream t, Monad m) => m (t m a) -> t m a
595concatM generator = concatMapM (\() -> generator) (fromPure ())
597-- | Like 'foldMany' but appends empty fold output if the fold and stream
598-- termination aligns:
600-- >>> f = Fold.take 2 Fold.sum
601-- >>> Stream.toList $ Stream.foldManyPost f $ Stream.fromList []
603-- >>> Stream.toList $ Stream.foldManyPost f $ Stream.fromList [1..9]
605-- >>> Stream.toList $ Stream.foldManyPost f $ Stream.fromList [1..10]
610{-# INLINE foldManyPost #-}
612 :: (IsStream t, Monad m)
616foldManyPost f m = fromStreamD $ D.foldManyPost f (toStreamD m)
618------------------------------------------------------------------------------
619-- Split stream and fold
620------------------------------------------------------------------------------
623-- > intercalate . splitOnSeq == id
624-- prop> (\f -> unsafePerformIO . Stream.toList . f . Stream.fromList) (Stream.intercalate Unfold.fromList " " . Stream.splitOnSeq (Array.fromList " ") Fold.toList) xs == xs
626-- | Like 'splitOn' but the separator is a sequence of elements instead of a
629-- For illustration, let's define a function that operates on pure lists:
631-- >>> splitOnSeq' pat xs = Stream.toList $ Stream.splitOnSeq (Array.fromList pat) Fold.toList (Stream.fromList xs)
633-- >>> splitOnSeq' "" "hello"
634-- ["h","e","l","l","o"]
636-- >>> splitOnSeq' "hello" ""
639-- >>> splitOnSeq' "hello" "hello"
642-- >>> splitOnSeq' "x" "hello"
645-- >>> splitOnSeq' "h" "hello"
648-- >>> splitOnSeq' "o" "hello"
651-- >>> splitOnSeq' "e" "hello"
654-- >>> splitOnSeq' "l" "hello"
657-- >>> splitOnSeq' "ll" "hello"
660-- 'splitOnSeq' is an inverse of 'intercalate'. The following law always holds:
662-- > intercalate . splitOnSeq == id
664-- The following law holds when the separator is non-empty and contains none of
665-- the elements present in the input lists:
667-- > splitOnSeq . intercalate == id
669-- >>> splitOnSeq pat f = Stream.foldManyPost (Fold.takeEndBySeq_ pat f)
673-- XXX We can use a polymorphic vector implemented by Array# to represent the
674-- sequence, that way we can avoid the Storable constraint. If we still need
675-- Storable Array for performance, we can use a separate splitOnArray API for
676-- that. We can also have an API where the sequence itself is a lazy stream, so
677-- that we can search files in files for example.
678{-# INLINE splitOnSeq #-}
680 :: (IsStream t, MonadIO m, Unboxed a, Enum a, Eq a)
681 => Array a -> Fold m a b -> t m a -> t m b
683 IsStream.fromStreamD $ D.splitOnSeq patt f (IsStream.toStreamD m)
684-- XXX This may have a problem if the stream terminates and we start extracting
685-- the fold and then the fold terminates before consuming all the buffered
686-- input. We have no way to supply the buffered input back to the driver.
687-- splitOnSeq patt f =
688 -- foldManyPost (Fold.takeEndBySeq_ patt f)
690------------------------------------------------------------------------------
692------------------------------------------------------------------------------
694-- | Like 'zipWith' but using a monadic zipping function.
697{-# INLINE zipWithM #-}
698zipWithM :: (IsStream t, Monad m) => (a -> b -> m c) -> t m a -> t m b -> t m c
701 $ D.zipWithM f (IsStream.toStreamD m1) (IsStream.toStreamD m2)
703-- | Stream @a@ is evaluated first, followed by stream @b@, the resulting
704-- elements @a@ and @b@ are then zipped using the supplied zip function and the
705-- result @c@ is yielded to the consumer.
707-- If stream @a@ or stream @b@ ends, the zipped stream ends. If stream @b@ ends
708-- first, the element @a@ from previous evaluation of stream @a@ is discarded.
711-- > D.toList $ D.zipWith (+) (D.fromList [1,2,3]) (D.fromList [4,5,6])
716{-# INLINE zipWith #-}
717zipWith :: (IsStream t, Monad m) => (a -> b -> c) -> t m a -> t m b -> t m c
720 $ D.zipWith f (IsStream.toStreamD m1) (IsStream.toStreamD m2)
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