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 qualified Foreign.Storable as Storable (Storable)
73import Streamly.Internal.Control.Concurrent (MonadAsync)
74import Streamly.Internal.Data.Array.Unboxed.Type (Array)
75import Streamly.Internal.Data.Fold.Type (Fold (..))
76import Streamly.Internal.Data.Stream.IsStream.Combinators (maxYields)
77import Streamly.Internal.Data.Stream.IsStream.Type
78 (IsStream(..), fromStreamD, toStreamD, fromStreamS, toStreamS)
79import Streamly.Internal.Data.Stream.Serial (SerialT)
80import Streamly.Internal.Data.Time.Units (AbsTime, RelTime64, addToAbsTime64)
81import Streamly.Internal.System.IO (defaultChunkSize)
82import Streamly.Internal.Data.Unboxed (Unboxed)
84import qualified Streamly.Internal.Data.Array.Unboxed.Type as A
85import qualified Streamly.Internal.Data.Stream.Async as Async
86import qualified Streamly.Internal.Data.Stream.IsStream.Type as IsStream
87import qualified Streamly.Internal.Data.Stream.Parallel as Par
88import qualified Streamly.Internal.Data.Stream.StreamK.Type as K
89import qualified Streamly.Internal.Data.Stream.StreamD as D
90#ifdef USE_STREAMK_ONLY
91import qualified Streamly.Internal.Data.Stream.StreamK as S
93import qualified Streamly.Internal.Data.Stream.StreamD as S
95import qualified Streamly.Internal.Data.Stream as Stream
97import Prelude hiding (take, takeWhile, drop, reverse, concatMap, map, zipWith)
102-- >>> import Control.Concurrent (threadDelay)
103-- >>> import Control.Monad (join)
104-- >>> import Control.Monad.Trans.Class (lift)
105-- >>> import Data.Function (fix, (&))
106-- >>> import Data.Semigroup (cycle1)
107-- >>> import Prelude hiding (take, takeWhile, drop, reverse)
108-- >>> import System.IO.Unsafe (unsafePerformIO)
109-- >>> import qualified Streamly.Prelude as Stream
110-- >>> import Streamly.Internal.Data.Stream.IsStream as Stream
111-- >>> import qualified Streamly.Data.Array.Unboxed as Array
112-- >>> import qualified Streamly.Data.Fold as Fold
113-- >>> import qualified Streamly.Internal.Data.Fold as Fold
114-- >>> import qualified Streamly.Data.Unfold as Unfold
116------------------------------------------------------------------------------
118------------------------------------------------------------------------------
120-- Faster than fromEffect because there is no bind.
124-- fromPure a = a \`cons` nil
127-- Create a singleton stream from a pure value.
129-- The following holds in monadic streams, but not in Zip streams:
133-- fromPure = fromEffect . pure
136-- In Zip applicative streams 'fromPure' is not the same as 'pure' because in that
137-- case 'pure' is equivalent to 'repeat' instead. 'fromPure' and 'pure' are
138-- equally efficient, in other cases 'fromPure' may be slightly more efficient
139-- than the other equivalent definitions.
141-- /Since: 0.8.0 (Renamed yield to fromPure)/
143{-# INLINE fromPure #-}
144fromPure :: IsStream t => a -> t m a
145fromPure = fromStream . K.fromPure
147-- | Same as 'fromPure'
150{-# DEPRECATED yield "Please use fromPure instead." #-}
152yield :: IsStream t => a -> t m a
157-- fromEffect m = m \`consM` nil
160-- Create a singleton stream from a monadic action.
163-- > Stream.toList $ Stream.fromEffect getLine
168-- /Since: 0.8.0 (Renamed yieldM to fromEffect)/
170{-# INLINE fromEffect #-}
171fromEffect :: (Monad m, IsStream t) => m a -> t m a
172fromEffect = fromStream . K.fromEffect
174-- | Same as 'fromEffect'
177{-# DEPRECATED yieldM "Please use fromEffect instead." #-}
179yieldM :: (Monad m, IsStream t) => m a -> t m a
182-- >>> repeatM = fix . consM
183-- >>> repeatM = cycle1 . fromEffect
185-- Generate a stream by repeatedly executing a monadic action forever.
189-- Stream.repeatM (threadDelay 1000000 >> print 1)
195-- /Concurrent, infinite (do not use with 'fromParallel')/
198{-# INLINE_EARLY repeatM #-}
199repeatM :: (IsStream t, MonadAsync m) => m a -> t m a
200repeatM = K.repeatMWith IsStream.consM
202{-# RULES "repeatM serial" repeatM = repeatMSerial #-}
203{-# INLINE repeatMSerial #-}
204repeatMSerial :: MonadAsync m => m a -> SerialT m a
205repeatMSerial = fromStreamS . S.repeatM
207------------------------------------------------------------------------------
208-- Generation - Time related
209------------------------------------------------------------------------------
211-- | @timesWith g@ returns a stream of time value tuples. The first component
212-- of the tuple is an absolute time reference (epoch) denoting the start of the
213-- stream and the second component is a time relative to the reference.
215-- The argument @g@ specifies the granularity of the relative time in seconds.
216-- A lower granularity clock gives higher precision but is more expensive in
217-- terms of CPU usage. Any granularity lower than 1 ms is treated as 1 ms.
219-- >>> import Control.Concurrent (threadDelay)
220-- >>> import Streamly.Internal.Data.Stream.IsStream.Common as Stream (timesWith)
221-- >>> Stream.mapM_ (\x -> print x >> threadDelay 1000000) $ Stream.take 3 $ Stream.timesWith 0.01
222-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),RelTime64 (NanoSecond64 ...))
223-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),RelTime64 (NanoSecond64 ...))
224-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),RelTime64 (NanoSecond64 ...))
226-- Note: This API is not safe on 32-bit machines.
230{-# INLINE timesWith #-}
231timesWith :: (IsStream t, MonadAsync m) => Double -> t m (AbsTime, RelTime64)
232timesWith g = fromStreamD $ D.times g
234-- | @absTimesWith g@ returns a stream of absolute timestamps using a clock of
235-- granularity @g@ specified in seconds. A low granularity clock is more
236-- expensive in terms of CPU usage. Any granularity lower than 1 ms is treated
239-- >>> Stream.mapM_ print $ Stream.delayPre 1 $ Stream.take 3 $ absTimesWith 0.01
240-- AbsTime (TimeSpec {sec = ..., nsec = ...})
241-- AbsTime (TimeSpec {sec = ..., nsec = ...})
242-- AbsTime (TimeSpec {sec = ..., nsec = ...})
244-- Note: This API is not safe on 32-bit machines.
248{-# INLINE absTimesWith #-}
249absTimesWith :: (IsStream t, MonadAsync m, Functor (t m))
250 => Double -> t m AbsTime
251absTimesWith = fmap (uncurry addToAbsTime64) . timesWith
253-- | @relTimesWith g@ returns a stream of relative time values starting from 0,
254-- using a clock of granularity @g@ specified in seconds. A low granularity
255-- clock is more expensive in terms of CPU usage. Any granularity lower than 1
256-- ms is treated as 1 ms.
258-- >>> Stream.mapM_ print $ Stream.delayPre 1 $ Stream.take 3 $ Stream.relTimesWith 0.01
259-- RelTime64 (NanoSecond64 ...)
260-- RelTime64 (NanoSecond64 ...)
261-- RelTime64 (NanoSecond64 ...)
263-- Note: This API is not safe on 32-bit machines.
267{-# INLINE relTimesWith #-}
268relTimesWith :: (IsStream t, MonadAsync m, Functor (t m))
269 => Double -> t m RelTime64
270relTimesWith = fmap snd . timesWith
272------------------------------------------------------------------------------
273-- Elimination - Running a Fold
274------------------------------------------------------------------------------
276-- | We can create higher order folds using 'foldContinue'. We can fold a
277-- number of streams to a given fold efficiently with full stream fusion. For
278-- example, to fold a list of streams on the same sum fold:
280-- >>> concatFold = Prelude.foldl Stream.foldContinue Fold.sum
282-- >>> fold f = Fold.finish . Stream.foldContinue f
285{-# INLINE foldContinue #-}
286foldContinue :: Monad m => Fold m a b -> SerialT m a -> Fold m a b
287foldContinue f s = D.foldContinue f $ IsStream.toStreamD s
289------------------------------------------------------------------------------
291------------------------------------------------------------------------------
301-- > S.toList $ S.map (+1) $ S.fromList [1,2,3]
307map :: (IsStream t, Monad m) => (a -> b) -> t m a -> t m b
308map f = fromStreamD . D.map f . toStreamD
310-- | @scanlMAfter' accumulate initial done stream@ is like 'scanlM'' except
311-- that it provides an additional @done@ function to be applied on the
312-- accumulator when the stream stops. The result of @done@ is also emitted in
315-- This function can be used to allocate a resource in the beginning of the
316-- scan and release it when the stream ends or to flush the internal state of
317-- the scan at the end.
321{-# INLINE scanlMAfter' #-}
322scanlMAfter' :: (IsStream t, Monad m)
323 => (b -> a -> m b) -> m b -> (b -> m b) -> t m a -> t m b
324scanlMAfter' step initial done stream =
325 fromStreamD $ D.scanlMAfter' step initial done $ toStreamD stream
327{-# INLINE postscanlMAfter' #-}
328postscanlMAfter' :: (IsStream t, Monad m)
329 => (b -> a -> m b) -> m b -> (b -> m b) -> t m a -> t m b
330postscanlMAfter' step initial done stream =
331 fromStreamD $ D.postscanlMAfter' step initial done $ toStreamD stream
333-- XXX this needs to be concurrent
334-- | Like 'postscanl'' but with a monadic step function and a monadic seed.
336-- >>> postscanlM' f z xs = Stream.drop 1 $ Stream.scanlM' f z xs
340-- /Since: 0.8.0 (signature change)/
341{-# INLINE postscanlM' #-}
342postscanlM' :: (IsStream t, Monad m) => (b -> a -> m b) -> m b -> t m a -> t m b
343postscanlM' step z m = fromStreamD $ D.postscanlM' step z $ toStreamD m
347-- The stateful step function can be simplified to @(s -> a -> m b)@ to provide
348-- a read-only environment. However, that would just be 'mapM'.
350-- The initial action could be @m (s, Maybe b)@, and we can also add a final
351-- action @s -> m (Maybe b)@. This can be used to get pre/post scan like
352-- functionality and also to flush the state in the end like scanlMAfter'.
353-- We can also use it along with a fusible version of bracket to get
354-- scanlMAfter' like functionality. See issue #677.
356-- This can be further generalized to a type similar to Fold/Parser, giving it
357-- filtering and parsing capability as well (this is in fact equivalent to
360-- smapM :: (s -> a -> m (Step s b)) -> m s -> t m a -> t m b
363-- | A stateful 'mapM', equivalent to a left scan, more like mapAccumL.
364-- Hopefully, this is a better alternative to @scan@. Separation of state from
365-- the output makes it easier to think in terms of a shared state, and also
366-- makes it easier to keep the state fully strict and the output lazy.
368-- See also: 'scanlM''
373smapM :: (IsStream t, Monad m) =>
378smapM step initial stream =
379 -- XXX implement this directly instead of using scanlM'
380 -- Once we have postscanlM' with monadic initial we can use this code
381 -- let r = postscanlM'
382 -- (\(s, _) a -> step s a)
383 -- (fmap (,undefined) initial)
386 (\(s, _) a -> step s a)
387 (fmap (,undefined) initial)
391------------------------------------------------------------------------------
392-- Transformation - Trimming
393------------------------------------------------------------------------------
395-- | Take first 'n' elements from the stream and discard the rest.
399take :: (IsStream t, Monad m) => Int -> t m a -> t m a
400take n m = fromStreamS $ S.take n $ toStreamS
401 (maxYields (Just (fromIntegral n)) m)
403-- | End the stream as soon as the predicate fails on an element.
406{-# INLINE takeWhile #-}
407takeWhile :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m a
408takeWhile p m = fromStreamS $ S.takeWhile p $ toStreamS m
410{-# INLINE takeEndBy #-}
411takeEndBy :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m a
412takeEndBy p m = fromStreamD $ D.takeEndBy p $ toStreamD m
414-- | Discard first 'n' elements from the stream and take the rest.
418drop :: (IsStream t, Monad m) => Int -> t m a -> t m a
419drop n m = fromStreamS $ S.drop n $ toStreamS m
421------------------------------------------------------------------------------
423------------------------------------------------------------------------------
425-- | Find all the indices where the element in the stream satisfies the given
428-- > findIndices = fold Fold.findIndices
431{-# INLINE findIndices #-}
432findIndices :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m Int
433findIndices p m = fromStreamS $ S.findIndices p (toStreamS m)
435------------------------------------------------------------------------------
436-- Transformation by Inserting
437------------------------------------------------------------------------------
439-- intersperseM = intersperseBySpan 1
441-- | Insert an effect and its output before consuming an element of a stream
442-- except the first one.
444-- >>> Stream.toList $ Stream.trace putChar $ Stream.intersperseM (putChar '.' >> return ',') $ Stream.fromList "hello"
445-- h.,e.,l.,l.,o"h,e,l,l,o"
447-- Be careful about the order of effects. In the above example we used trace
448-- after the intersperse, if we use it before the intersperse the output would
449-- be he.l.l.o."h,e,l,l,o".
451-- >>> Stream.toList $ Stream.intersperseM (putChar '.' >> return ',') $ Stream.trace putChar $ Stream.fromList "hello"
452-- he.l.l.o."h,e,l,l,o"
455{-# INLINE intersperseM #-}
456intersperseM :: (IsStream t, MonadAsync m) => m a -> t m a -> t m a
457intersperseM m = fromStreamS . S.intersperseM m . toStreamS
459-- | Intersperse a monadic action into the input stream after every @n@
463-- > import Control.Concurrent (threadDelay)
464-- > Stream.drain $ Stream.interjectSuffix 1 (putChar ',') $ Stream.mapM (\x -> threadDelay 1000000 >> putChar x) $ Stream.fromList "hello"
469{-# INLINE interjectSuffix #-}
471 :: (IsStream t, MonadAsync m)
472 => Double -> m a -> t m a -> t m a
473interjectSuffix n f xs = xs `parallelFst` repeatM timed
474 where timed = liftIO (threadDelay (round $ n * 1000000)) >> f
476------------------------------------------------------------------------------
477-- Transformation by Reordering
478------------------------------------------------------------------------------
480-- XXX Use a compact region list to temporarily store the list, in both reverse
481-- as well as in reverse'.
483-- /Note:/ 'reverse'' is much faster than this, use that when performance
486-- | Returns the elements of the stream in reverse order. The stream must be
487-- finite. Note that this necessarily buffers the entire stream in memory.
489-- >>> reverse = Stream.foldlT (flip Stream.cons) Stream.nil
491-- /Since 0.7.0 (Monad m constraint)/
494{-# INLINE reverse #-}
495reverse :: (IsStream t, Monad m) => t m a -> t m a
496reverse s = fromStreamS $ S.reverse $ toStreamS s
498-- | Like 'reverse' but several times faster, requires a 'Storable' instance.
501{-# INLINE reverse' #-}
502reverse' :: (IsStream t, MonadIO m, Unboxed a) => t m a -> t m a
503-- reverse' s = fromStreamD $ D.reverse' $ toStreamD s
506 . A.flattenArraysRev -- unfoldMany A.readRev
510 . A.arraysOf defaultChunkSize
513------------------------------------------------------------------------------
514-- Concurrent Transformations and Combining
515------------------------------------------------------------------------------
517-- | Make the stream producer and consumer run concurrently by introducing a
518-- buffer between them. The producer thread evaluates the input stream until
519-- the buffer fills, it terminates if the buffer is full and a worker thread is
520-- kicked off again to evaluate the remaining stream when there is space in the
521-- buffer. The consumer consumes the stream lazily from the buffer.
523-- /Since: 0.2.0 (Streamly)/
527{-# INLINE_NORMAL mkAsync #-}
528mkAsync :: (IsStream t, MonadAsync m) => t m a -> t m a
529mkAsync = fromStreamD . Async.mkAsyncD . toStreamD
531-- Compare with mkAsync. mkAsync uses an Async style SVar whereas this uses a
532-- parallel style SVar for evaluation. Currently, parallel style cannot use
533-- rate control whereas Async style can use rate control. In async style SVar
534-- the worker thread terminates when the buffer is full whereas in Parallel
537-- | Make the stream producer and consumer run concurrently by introducing a
538-- buffer between them. The producer thread evaluates the input stream until
539-- the buffer fills, it blocks if the buffer is full until there is space in
540-- the buffer. The consumer consumes the stream lazily from the buffer.
542-- @mkParallel = IsStream.fromStreamD . mkParallelD . IsStream.toStreamD@
546{-# INLINE_NORMAL mkParallel #-}
547mkParallel :: (IsStream t, MonadAsync m) => t m a -> t m a
548mkParallel = fromStreamD . Par.mkParallelD . toStreamD
550-- | Like `parallel` but stops the output as soon as the first stream stops.
553{-# INLINE parallelFst #-}
554parallelFst :: (IsStream t, MonadAsync m) => t m a -> t m a -> t m a
555parallelFst m1 m2 = fromStream $ Par.parallelFstK (toStream m1) (toStream m2)
557------------------------------------------------------------------------------
558-- Combine streams and flatten
559------------------------------------------------------------------------------
561-- | Map a stream producing monadic function on each element of the stream
562-- and then flatten the results into a single stream. Since the stream
563-- generation function is monadic, unlike 'concatMap', it can produce an
564-- effect at the beginning of each iteration of the inner loop.
567{-# INLINE concatMapM #-}
568concatMapM :: (IsStream t, Monad m) => (a -> m (t m b)) -> t m a -> t m b
569concatMapM f m = fromStreamD $ D.concatMapM (fmap toStreamD . f) (toStreamD m)
571-- | Map a stream producing function on each element of the stream and then
572-- flatten the results into a single stream.
574-- >>> concatMap f = Stream.concatMapM (return . f)
575-- >>> concatMap f = Stream.concatMapWith Stream.serial f
576-- >>> concatMap f = Stream.concat . Stream.map f
577-- >>> concatMap f = Stream.unfoldMany (Unfold.lmap f Unfold.fromStream)
580{-# INLINE concatMap #-}
581concatMap ::(IsStream t, Monad m) => (a -> t m b) -> t m a -> t m b
582concatMap f m = fromStreamD $ D.concatMap (toStreamD . f) (toStreamD m)
584-- | Given a stream value in the underlying monad, lift and join the underlying
585-- monad with the stream monad.
587-- >>> concatM = Stream.concat . Stream.fromEffect
588-- >>> concatM = Stream.concat . lift -- requires (MonadTrans t)
589-- >>> concatM = join . lift -- requires (MonadTrans t, Monad (t m))
591-- See also: 'concat', 'sequence'
595{-# INLINE concatM #-}
596concatM :: (IsStream t, Monad m) => m (t m a) -> t m a
597concatM generator = concatMapM (\() -> generator) (fromPure ())
599-- | Like 'foldMany' but appends empty fold output if the fold and stream
600-- termination aligns:
602-- >>> f = Fold.take 2 Fold.sum
603-- >>> Stream.toList $ Stream.foldManyPost f $ Stream.fromList []
605-- >>> Stream.toList $ Stream.foldManyPost f $ Stream.fromList [1..9]
607-- >>> Stream.toList $ Stream.foldManyPost f $ Stream.fromList [1..10]
612{-# INLINE foldManyPost #-}
614 :: (IsStream t, Monad m)
618foldManyPost f m = fromStreamD $ D.foldManyPost f (toStreamD m)
620------------------------------------------------------------------------------
621-- Split stream and fold
622------------------------------------------------------------------------------
625-- > intercalate . splitOnSeq == id
626-- prop> (\f -> unsafePerformIO . Stream.toList . f . Stream.fromList) (Stream.intercalate Unfold.fromList " " . Stream.splitOnSeq (Array.fromList " ") Fold.toList) xs == xs
628-- | Like 'splitOn' but the separator is a sequence of elements instead of a
631-- For illustration, let's define a function that operates on pure lists:
633-- >>> splitOnSeq' pat xs = Stream.toList $ Stream.splitOnSeq (Array.fromList pat) Fold.toList (Stream.fromList xs)
635-- >>> splitOnSeq' "" "hello"
636-- ["h","e","l","l","o"]
638-- >>> splitOnSeq' "hello" ""
641-- >>> splitOnSeq' "hello" "hello"
644-- >>> splitOnSeq' "x" "hello"
647-- >>> splitOnSeq' "h" "hello"
650-- >>> splitOnSeq' "o" "hello"
653-- >>> splitOnSeq' "e" "hello"
656-- >>> splitOnSeq' "l" "hello"
659-- >>> splitOnSeq' "ll" "hello"
662-- 'splitOnSeq' is an inverse of 'intercalate'. The following law always holds:
664-- > intercalate . splitOnSeq == id
666-- The following law holds when the separator is non-empty and contains none of
667-- the elements present in the input lists:
669-- > splitOnSeq . intercalate == id
671-- >>> splitOnSeq pat f = Stream.foldManyPost (Fold.takeEndBySeq_ pat f)
675-- XXX We can use a polymorphic vector implemented by Array# to represent the
676-- sequence, that way we can avoid the Storable constraint. If we still need
677-- Storable Array for performance, we can use a separate splitOnArray API for
678-- that. We can also have an API where the sequence itself is a lazy stream, so
679-- that we can search files in files for example.
680{-# INLINE splitOnSeq #-}
682 :: (IsStream t, MonadIO m, Storable.Storable a, Unboxed a, Enum a, Eq a)
683 => Array a -> Fold m a b -> t m a -> t m b
685 IsStream.fromStreamD $ D.splitOnSeq patt f (IsStream.toStreamD m)
686-- XXX This may have a problem if the stream terminates and we start extracting
687-- the fold and then the fold terminates before consuming all the buffered
688-- input. We have no way to supply the buffered input back to the driver.
689-- splitOnSeq patt f =
690 -- foldManyPost (Fold.takeEndBySeq_ patt f)
692------------------------------------------------------------------------------
694------------------------------------------------------------------------------
696-- | Like 'zipWith' but using a monadic zipping function.
699{-# INLINE zipWithM #-}
700zipWithM :: (IsStream t, Monad m) => (a -> b -> m c) -> t m a -> t m b -> t m c
703 $ S.zipWithM f (IsStream.toStreamS m1) (IsStream.toStreamS m2)
705-- | Stream @a@ is evaluated first, followed by stream @b@, the resulting
706-- elements @a@ and @b@ are then zipped using the supplied zip function and the
707-- result @c@ is yielded to the consumer.
709-- If stream @a@ or stream @b@ ends, the zipped stream ends. If stream @b@ ends
710-- first, the element @a@ from previous evaluation of stream @a@ is discarded.
713-- > S.toList $ S.zipWith (+) (S.fromList [1,2,3]) (S.fromList [4,5,6])
718{-# INLINE zipWith #-}
719zipWith :: (IsStream t, Monad m) => (a -> b -> c) -> t m a -> t m b -> t m c
722 $ S.zipWith f (IsStream.toStreamS m1) (IsStream.toStreamS 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