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
68import Control.Concurrent (threadDelay)
69import Control.Monad.IO.Class (MonadIO(..))
70import Foreign.Storable (Storable)
71import Streamly.Internal.Control.Concurrent (MonadAsync)
72import Streamly.Internal.Data.Array.Foreign.Type (Array)
73import Streamly.Internal.Data.Fold.Type (Fold (..))
74import Streamly.Internal.Data.Stream.IsStream.Combinators (maxYields)
75import Streamly.Internal.Data.Stream.IsStream.Type
76 (IsStream(..), fromStreamD, toStreamD, fromStreamS, toStreamS)
77import Streamly.Internal.Data.Stream.Serial (SerialT)
78import Streamly.Internal.Data.Time.Units (AbsTime, RelTime64, addToAbsTime64)
80import qualified Streamly.Internal.Data.Array.Foreign.Type as A
81import qualified Streamly.Internal.Data.Stream.Async as Async
82import qualified Streamly.Internal.Data.Stream.IsStream.Type as IsStream
83import qualified Streamly.Internal.Data.Stream.Parallel as Par
84import qualified Streamly.Internal.Data.Stream.StreamK.Type as K
85import qualified Streamly.Internal.Data.Stream.StreamD as D
86#ifdef USE_STREAMK_ONLY
87import qualified Streamly.Internal.Data.Stream.StreamK as S
89import qualified Streamly.Internal.Data.Stream.StreamD as S
91import Streamly.Internal.System.IO (defaultChunkSize)
93import Prelude hiding (take, takeWhile, drop, reverse, concatMap, map, zipWith)
98-- >>> import Control.Concurrent (threadDelay)
99-- >>> import Control.Monad (join)
100-- >>> import Control.Monad.Trans.Class (lift)
101-- >>> import Data.Function (fix, (&))
102-- >>> import Data.Semigroup (cycle1)
103-- >>> import Prelude hiding (take, takeWhile, drop, reverse)
104-- >>> import System.IO.Unsafe (unsafePerformIO)
105-- >>> import qualified Streamly.Prelude as Stream
106-- >>> import Streamly.Internal.Data.Stream.IsStream as Stream
107-- >>> import qualified Streamly.Data.Array.Foreign as Array
108-- >>> import qualified Streamly.Data.Fold as Fold
109-- >>> import qualified Streamly.Internal.Data.Fold as Fold
110-- >>> import qualified Streamly.Data.Unfold as Unfold
112------------------------------------------------------------------------------
114------------------------------------------------------------------------------
116-- Faster than fromEffect because there is no bind.
120-- fromPure a = a \`cons` nil
123-- Create a singleton stream from a pure value.
125-- The following holds in monadic streams, but not in Zip streams:
129-- fromPure = fromEffect . pure
132-- In Zip applicative streams 'fromPure' is not the same as 'pure' because in that
133-- case 'pure' is equivalent to 'repeat' instead. 'fromPure' and 'pure' are
134-- equally efficient, in other cases 'fromPure' may be slightly more efficient
135-- than the other equivalent definitions.
137-- /Since: 0.8.0 (Renamed yield to fromPure)/
139{-# INLINE fromPure #-}
140fromPure :: IsStream t => a -> t m a
141fromPure = fromStream . K.fromPure
143-- | Same as 'fromPure'
146{-# DEPRECATED yield "Please use fromPure instead." #-}
148yield :: IsStream t => a -> t m a
153-- fromEffect m = m \`consM` nil
156-- Create a singleton stream from a monadic action.
159-- > Stream.toList $ Stream.fromEffect getLine
164-- /Since: 0.8.0 (Renamed yieldM to fromEffect)/
166{-# INLINE fromEffect #-}
167fromEffect :: (Monad m, IsStream t) => m a -> t m a
168fromEffect = fromStream . K.fromEffect
170-- | Same as 'fromEffect'
173{-# DEPRECATED yieldM "Please use fromEffect instead." #-}
175yieldM :: (Monad m, IsStream t) => m a -> t m a
178-- >>> repeatM = fix . consM
179-- >>> repeatM = cycle1 . fromEffect
181-- Generate a stream by repeatedly executing a monadic action forever.
185-- Stream.repeatM (threadDelay 1000000 >> print 1)
191-- /Concurrent, infinite (do not use with 'fromParallel')/
194{-# INLINE_EARLY repeatM #-}
195repeatM :: (IsStream t, MonadAsync m) => m a -> t m a
196repeatM = K.repeatMWith IsStream.consM
198{-# RULES "repeatM serial" repeatM = repeatMSerial #-}
199{-# INLINE repeatMSerial #-}
200repeatMSerial :: MonadAsync m => m a -> SerialT m a
201repeatMSerial = fromStreamS . S.repeatM
203------------------------------------------------------------------------------
204-- Generation - Time related
205------------------------------------------------------------------------------
207-- | @timesWith g@ returns a stream of time value tuples. The first component
208-- of the tuple is an absolute time reference (epoch) denoting the start of the
209-- stream and the second component is a time relative to the reference.
211-- The argument @g@ specifies the granularity of the relative time in seconds.
212-- A lower granularity clock gives higher precision but is more expensive in
213-- terms of CPU usage. Any granularity lower than 1 ms is treated as 1 ms.
215-- >>> import Control.Concurrent (threadDelay)
216-- >>> import Streamly.Internal.Data.Stream.IsStream.Common as Stream (timesWith)
217-- >>> Stream.mapM_ (\x -> print x >> threadDelay 1000000) $ Stream.take 3 $ Stream.timesWith 0.01
218-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),RelTime64 (NanoSecond64 ...))
219-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),RelTime64 (NanoSecond64 ...))
220-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),RelTime64 (NanoSecond64 ...))
222-- Note: This API is not safe on 32-bit machines.
226{-# INLINE timesWith #-}
227timesWith :: (IsStream t, MonadAsync m) => Double -> t m (AbsTime, RelTime64)
228timesWith g = fromStreamD $ D.times g
230-- | @absTimesWith g@ returns a stream of absolute timestamps using a clock of
231-- granularity @g@ specified in seconds. A low granularity clock is more
232-- expensive in terms of CPU usage. Any granularity lower than 1 ms is treated
235-- >>> Stream.mapM_ print $ Stream.delayPre 1 $ Stream.take 3 $ absTimesWith 0.01
236-- AbsTime (TimeSpec {sec = ..., nsec = ...})
237-- AbsTime (TimeSpec {sec = ..., nsec = ...})
238-- AbsTime (TimeSpec {sec = ..., nsec = ...})
240-- Note: This API is not safe on 32-bit machines.
244{-# INLINE absTimesWith #-}
245absTimesWith :: (IsStream t, MonadAsync m, Functor (t m))
246 => Double -> t m AbsTime
247absTimesWith = fmap (uncurry addToAbsTime64) . timesWith
249-- | @relTimesWith g@ returns a stream of relative time values starting from 0,
250-- using a clock of granularity @g@ specified in seconds. A low granularity
251-- clock is more expensive in terms of CPU usage. Any granularity lower than 1
252-- ms is treated as 1 ms.
254-- >>> Stream.mapM_ print $ Stream.delayPre 1 $ Stream.take 3 $ Stream.relTimesWith 0.01
255-- RelTime64 (NanoSecond64 ...)
256-- RelTime64 (NanoSecond64 ...)
257-- RelTime64 (NanoSecond64 ...)
259-- Note: This API is not safe on 32-bit machines.
263{-# INLINE relTimesWith #-}
264relTimesWith :: (IsStream t, MonadAsync m, Functor (t m))
265 => Double -> t m RelTime64
266relTimesWith = fmap snd . timesWith
268------------------------------------------------------------------------------
269-- Elimination - Running a Fold
270------------------------------------------------------------------------------
272-- | We can create higher order folds using 'foldOn'. We can fold a number of
273-- streams to a given fold efficiently with full stream fusion. For example, to
274-- fold a list of streams on the same sum fold:
276-- >>> concatFold = Prelude.foldl Stream.foldOn Fold.sum
278-- >>> fold f = Fold.finish . Stream.foldOn f
282foldOn :: Monad m => Fold m a b -> SerialT m a -> Fold m a b
283foldOn f s = D.foldOn f $ IsStream.toStreamD s
285-- | Fold a stream using the supplied left 'Fold' and reducing the resulting
286-- expression strictly at each step. The behavior is similar to 'foldl''. A
287-- 'Fold' can terminate early without consuming the full stream. See the
288-- documentation of individual 'Fold's for termination behavior.
290-- >>> Stream.fold Fold.sum (Stream.enumerateFromTo 1 100)
293-- Folds never fail, therefore, they produce a default value even when no input
294-- is provided. It means we can always fold an empty stream and get a valid
295-- result. For example:
297-- >>> Stream.fold Fold.sum Stream.nil
300-- However, 'foldMany' on an empty stream results in an empty stream.
301-- Therefore, @Stream.fold f@ is not the same as @Stream.head . Stream.foldMany
304-- @fold f = Stream.parse (Parser.fromFold f)@
308fold :: Monad m => Fold m a b -> SerialT m a -> m b
310 (b, _) <- fold_ fl strm
314fold_ :: Monad m => Fold m a b -> SerialT m a -> m (b, SerialT m a)
316 (b, str) <- D.fold_ fl $ IsStream.toStreamD strm
317 return $! (b, IsStream.fromStreamD str)
319------------------------------------------------------------------------------
321------------------------------------------------------------------------------
331-- > S.toList $ S.map (+1) $ S.fromList [1,2,3]
337map :: (IsStream t, Monad m) => (a -> b) -> t m a -> t m b
338map f = fromStreamD . D.map f . toStreamD
340-- | @scanlMAfter' accumulate initial done stream@ is like 'scanlM'' except
341-- that it provides an additional @done@ function to be applied on the
342-- accumulator when the stream stops. The result of @done@ is also emitted in
345-- This function can be used to allocate a resource in the beginning of the
346-- scan and release it when the stream ends or to flush the internal state of
347-- the scan at the end.
351{-# INLINE scanlMAfter' #-}
352scanlMAfter' :: (IsStream t, Monad m)
353 => (b -> a -> m b) -> m b -> (b -> m b) -> t m a -> t m b
354scanlMAfter' step initial done stream =
355 fromStreamD $ D.scanlMAfter' step initial done $ toStreamD stream
357-- XXX this needs to be concurrent
358-- | Like 'postscanl'' but with a monadic step function and a monadic seed.
360-- >>> postscanlM' f z xs = Stream.drop 1 $ Stream.scanlM' f z xs
364-- /Since: 0.8.0 (signature change)/
365{-# INLINE postscanlM' #-}
366postscanlM' :: (IsStream t, Monad m) => (b -> a -> m b) -> m b -> t m a -> t m b
367postscanlM' step z m = fromStreamD $ D.postscanlM' step z $ toStreamD m
371-- The stateful step function can be simplified to @(s -> a -> m b)@ to provide
372-- a read-only environment. However, that would just be 'mapM'.
374-- The initial action could be @m (s, Maybe b)@, and we can also add a final
375-- action @s -> m (Maybe b)@. This can be used to get pre/post scan like
376-- functionality and also to flush the state in the end like scanlMAfter'.
377-- We can also use it along with a fusible version of bracket to get
378-- scanlMAfter' like functionality. See issue #677.
380-- This can be further generalized to a type similar to Fold/Parser, giving it
381-- filtering and parsing capability as well (this is in fact equivalent to
384-- smapM :: (s -> a -> m (Step s b)) -> m s -> t m a -> t m b
387-- | A stateful 'mapM', equivalent to a left scan, more like mapAccumL.
388-- Hopefully, this is a better alternative to @scan@. Separation of state from
389-- the output makes it easier to think in terms of a shared state, and also
390-- makes it easier to keep the state fully strict and the output lazy.
392-- See also: 'scanlM''
397smapM :: (IsStream t, Monad m) =>
402smapM step initial stream =
403 -- XXX implement this directly instead of using scanlM'
404 -- Once we have postscanlM' with monadic initial we can use this code
405 -- let r = postscanlM'
406 -- (\(s, _) a -> step s a)
407 -- (fmap (,undefined) initial)
410 (\(s, _) a -> step s a)
411 (fmap (,undefined) initial)
415------------------------------------------------------------------------------
416-- Transformation - Trimming
417------------------------------------------------------------------------------
419-- | Take first 'n' elements from the stream and discard the rest.
423take :: (IsStream t, Monad m) => Int -> t m a -> t m a
424take n m = fromStreamS $ S.take n $ toStreamS
425 (maxYields (Just (fromIntegral n)) m)
427-- | End the stream as soon as the predicate fails on an element.
430{-# INLINE takeWhile #-}
431takeWhile :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m a
432takeWhile p m = fromStreamS $ S.takeWhile p $ toStreamS m
434{-# INLINE takeEndBy #-}
435takeEndBy :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m a
436takeEndBy p m = fromStreamD $ D.takeEndBy p $ toStreamD m
438-- | Discard first 'n' elements from the stream and take the rest.
442drop :: (IsStream t, Monad m) => Int -> t m a -> t m a
443drop n m = fromStreamS $ S.drop n $ toStreamS m
445------------------------------------------------------------------------------
447------------------------------------------------------------------------------
449-- | Find all the indices where the element in the stream satisfies the given
452-- > findIndices = fold Fold.findIndices
455{-# INLINE findIndices #-}
456findIndices :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m Int
457findIndices p m = fromStreamS $ S.findIndices p (toStreamS m)
459------------------------------------------------------------------------------
460-- Transformation by Inserting
461------------------------------------------------------------------------------
463-- intersperseM = intersperseBySpan 1
465-- | Insert an effect and its output before consuming an element of a stream
466-- except the first one.
468-- >>> Stream.toList $ Stream.trace putChar $ Stream.intersperseM (putChar '.' >> return ',') $ Stream.fromList "hello"
469-- h.,e.,l.,l.,o"h,e,l,l,o"
471-- Be careful about the order of effects. In the above example we used trace
472-- after the intersperse, if we use it before the intersperse the output would
473-- be he.l.l.o."h,e,l,l,o".
475-- >>> Stream.toList $ Stream.intersperseM (putChar '.' >> return ',') $ Stream.trace putChar $ Stream.fromList "hello"
476-- he.l.l.o."h,e,l,l,o"
479{-# INLINE intersperseM #-}
480intersperseM :: (IsStream t, MonadAsync m) => m a -> t m a -> t m a
481intersperseM m = fromStreamS . S.intersperseM m . toStreamS
483-- | Intersperse a monadic action into the input stream after every @n@
487-- > import Control.Concurrent (threadDelay)
488-- > Stream.drain $ Stream.interjectSuffix 1 (putChar ',') $ Stream.mapM (\x -> threadDelay 1000000 >> putChar x) $ Stream.fromList "hello"
493{-# INLINE interjectSuffix #-}
495 :: (IsStream t, MonadAsync m)
496 => Double -> m a -> t m a -> t m a
497interjectSuffix n f xs = xs `parallelFst` repeatM timed
498 where timed = liftIO (threadDelay (round $ n * 1000000)) >> f
500------------------------------------------------------------------------------
501-- Transformation by Reordering
502------------------------------------------------------------------------------
504-- XXX Use a compact region list to temporarily store the list, in both reverse
505-- as well as in reverse'.
507-- /Note:/ 'reverse'' is much faster than this, use that when performance
510-- | Returns the elements of the stream in reverse order. The stream must be
511-- finite. Note that this necessarily buffers the entire stream in memory.
513-- >>> reverse = Stream.foldlT (flip Stream.cons) Stream.nil
515-- /Since 0.7.0 (Monad m constraint)/
518{-# INLINE reverse #-}
519reverse :: (IsStream t, Monad m) => t m a -> t m a
520reverse s = fromStreamS $ S.reverse $ toStreamS s
522-- | Like 'reverse' but several times faster, requires a 'Storable' instance.
525{-# INLINE reverse' #-}
526reverse' :: (IsStream t, MonadIO m, Storable a) => t m a -> t m a
527-- reverse' s = fromStreamD $ D.reverse' $ toStreamD s
530 . A.flattenArraysRev -- unfoldMany A.readRev
534 . A.arraysOf defaultChunkSize
537------------------------------------------------------------------------------
538-- Concurrent Transformations and Combining
539------------------------------------------------------------------------------
541-- | Make the stream producer and consumer run concurrently by introducing a
542-- buffer between them. The producer thread evaluates the input stream until
543-- the buffer fills, it terminates if the buffer is full and a worker thread is
544-- kicked off again to evaluate the remaining stream when there is space in the
545-- buffer. The consumer consumes the stream lazily from the buffer.
547-- /Since: 0.2.0 (Streamly)/
551{-# INLINE_NORMAL mkAsync #-}
552mkAsync :: (IsStream t, MonadAsync m) => t m a -> t m a
553mkAsync = fromStreamD . Async.mkAsyncD . toStreamD
555-- Compare with mkAsync. mkAsync uses an Async style SVar whereas this uses a
556-- parallel style SVar for evaluation. Currently, parallel style cannot use
557-- rate control whereas Async style can use rate control. In async style SVar
558-- the worker thread terminates when the buffer is full whereas in Parallel
561-- | Make the stream producer and consumer run concurrently by introducing a
562-- buffer between them. The producer thread evaluates the input stream until
563-- the buffer fills, it blocks if the buffer is full until there is space in
564-- the buffer. The consumer consumes the stream lazily from the buffer.
566-- @mkParallel = IsStream.fromStreamD . mkParallelD . IsStream.toStreamD@
570{-# INLINE_NORMAL mkParallel #-}
571mkParallel :: (IsStream t, MonadAsync m) => t m a -> t m a
572mkParallel = fromStreamD . Par.mkParallelD . toStreamD
574-- | Like `parallel` but stops the output as soon as the first stream stops.
577{-# INLINE parallelFst #-}
578parallelFst :: (IsStream t, MonadAsync m) => t m a -> t m a -> t m a
579parallelFst m1 m2 = fromStream $ Par.parallelFstK (toStream m1) (toStream m2)
581------------------------------------------------------------------------------
582-- Combine streams and flatten
583------------------------------------------------------------------------------
585-- | Map a stream producing monadic function on each element of the stream
586-- and then flatten the results into a single stream. Since the stream
587-- generation function is monadic, unlike 'concatMap', it can produce an
588-- effect at the beginning of each iteration of the inner loop.
591{-# INLINE concatMapM #-}
592concatMapM :: (IsStream t, Monad m) => (a -> m (t m b)) -> t m a -> t m b
593concatMapM f m = fromStreamD $ D.concatMapM (fmap toStreamD . f) (toStreamD m)
595-- | Map a stream producing function on each element of the stream and then
596-- flatten the results into a single stream.
598-- >>> concatMap f = Stream.concatMapM (return . f)
599-- >>> concatMap f = Stream.concatMapWith Stream.serial f
600-- >>> concatMap f = Stream.concat . Stream.map f
601-- >>> concatMap f = Stream.unfoldMany (Unfold.lmap f Unfold.fromStream)
604{-# INLINE concatMap #-}
605concatMap ::(IsStream t, Monad m) => (a -> t m b) -> t m a -> t m b
606concatMap f m = fromStreamD $ D.concatMap (toStreamD . f) (toStreamD m)
608-- | Given a stream value in the underlying monad, lift and join the underlying
609-- monad with the stream monad.
611-- >>> concatM = Stream.concat . Stream.fromEffect
612-- >>> concatM = Stream.concat . lift -- requires (MonadTrans t)
613-- >>> concatM = join . lift -- requires (MonadTrans t, Monad (t m))
615-- See also: 'concat', 'sequence'
619{-# INLINE concatM #-}
620concatM :: (IsStream t, Monad m) => m (t m a) -> t m a
621concatM generator = concatMapM (\() -> generator) (fromPure ())
623------------------------------------------------------------------------------
624-- Split stream and fold
625------------------------------------------------------------------------------
628-- > intercalate . splitOnSeq == id
629-- prop> (\f -> unsafePerformIO . Stream.toList . f . Stream.fromList) (Stream.intercalate Unfold.fromList " " . Stream.splitOnSeq (Array.fromList " ") Fold.toList) xs == xs
631-- | Like 'splitOn' but the separator is a sequence of elements instead of a
634-- For illustration, let's define a function that operates on pure lists:
636-- >>> splitOnSeq' pat xs = Stream.toList $ Stream.splitOnSeq (Array.fromList pat) Fold.toList (Stream.fromList xs)
638-- >>> splitOnSeq' "" "hello"
639-- ["h","e","l","l","o"]
641-- >>> splitOnSeq' "hello" ""
644-- >>> splitOnSeq' "hello" "hello"
647-- >>> splitOnSeq' "x" "hello"
650-- >>> splitOnSeq' "h" "hello"
653-- >>> splitOnSeq' "o" "hello"
656-- >>> splitOnSeq' "e" "hello"
659-- >>> splitOnSeq' "l" "hello"
662-- >>> splitOnSeq' "ll" "hello"
665-- 'splitOnSeq' is an inverse of 'intercalate'. The following law always holds:
667-- > intercalate . splitOnSeq == id
669-- The following law holds when the separator is non-empty and contains none of
670-- the elements present in the input lists:
672-- > splitOnSeq . intercalate == id
676-- XXX We can use a polymorphic vector implemented by Array# to represent the
677-- sequence, that way we can avoid the Storable constraint. If we still need
678-- Storable Array for performance, we can use a separate splitOnArray API for
679-- that. We can also have an API where the sequence itself is a lazy stream, so
680-- that we can search files in files for example.
681{-# INLINE splitOnSeq #-}
683 :: (IsStream t, MonadIO m, Storable a, Enum a, Eq a)
684 => Array a -> Fold m a b -> t m a -> t m b
686 IsStream.fromStreamD $ D.splitOnSeq patt f (IsStream.toStreamD m)
688------------------------------------------------------------------------------
690------------------------------------------------------------------------------
692-- | Like 'zipWith' but using a monadic zipping function.
695{-# INLINE zipWithM #-}
696zipWithM :: (IsStream t, Monad m) => (a -> b -> m c) -> t m a -> t m b -> t m c
699 $ S.zipWithM f (IsStream.toStreamS m1) (IsStream.toStreamS m2)
701-- | Stream @a@ is evaluated first, followed by stream @b@, the resulting
702-- elements @a@ and @b@ are then zipped using the supplied zip function and the
703-- result @c@ is yielded to the consumer.
705-- If stream @a@ or stream @b@ ends, the zipped stream ends. If stream @b@ ends
706-- first, the element @a@ from previous evaluation of stream @a@ is discarded.
709-- > S.toList $ S.zipWith (+) (S.fromList [1,2,3]) (S.fromList [4,5,6])
714{-# INLINE zipWith #-}
715zipWith :: (IsStream t, Monad m) => (a -> b -> c) -> t m a -> t m b -> t m c
718 $ 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