1{-# OPTIONS_GHC -Wno-orphans #-}
4-- Module : Streamly.Internal.Data.Stream.IsStream.Generate
5-- Copyright : (c) 2017 Composewell Technologies
6-- License : BSD-3-Clause
7-- Maintainer : streamly@composewell.com
8-- Stability : experimental
11-- Most of the combinators in this module can be implemented as unfolds. Some
12-- of them however can only be expressed in terms StreamK e.g. cons/consM,
13-- fromFoldable, mfix. We can possibly remove those from this module which can
14-- be expressed as unfolds. Unless we want to use rewrite rules to rewrite them
15-- as StreamK when StreamK is used, avoiding conversion to StreamD. Will that
16-- help? Are there any other reasons to keep these and not use unfolds?
18module Streamly.Internal.Data.Stream.IsStream.Generate
91import Control.Monad.IO.Class (MonadIO(..))
92import Data.Void (Void)
93import Streamly.Internal.Control.Concurrent (MonadAsync)
94import Streamly.Internal.Data.Unfold.Type (Unfold)
95import Streamly.Internal.Data.SVar (Rate (..))
96import Streamly.Internal.Data.Stream.IsStream.Enumeration
97 (Enumerable(..), enumerate, enumerateTo)
98import Streamly.Internal.Data.Stream.IsStream.Common
99 ( absTimesWith, concatM, relTimesWith, timesWith, fromPure, fromEffect
100 , yield, yieldM, repeatM)
101import Streamly.Internal.Data.Stream.IsStream.Type
102 (IsStream (..), fromSerial, consM, fromStreamD)
103import Streamly.Internal.Data.Stream.Serial (SerialT)
104import Streamly.Internal.Data.Stream.WSerial (WSerialT)
105import Streamly.Internal.Data.Stream.Zip (ZipSerialM)
106import Streamly.Internal.Data.Time.Units (AbsTime , RelTime64, addToAbsTime64)
107import Streamly.Internal.Data.Unboxed (Unboxed)
109import qualified Streamly.Internal.Data.IORef.Unboxed as Unboxed
110import qualified Streamly.Internal.Data.Stream.IsStream.Type as IsStream
111import qualified Streamly.Internal.Data.Stream.Parallel as Par
112import qualified Streamly.Internal.Data.Stream.Serial as Serial
113import qualified Streamly.Internal.Data.Stream.StreamD.Generate as D
114import qualified Streamly.Internal.Data.Stream.StreamK.Type as K
115import qualified Streamly.Internal.Data.Stream.Type as Stream
116import qualified System.IO as IO
118import Prelude hiding (iterate, replicate, repeat)
122-- >>> import Data.Function ((&))
123-- >>> import Prelude hiding (iterate, replicate, repeat)
124-- >>> import qualified Streamly.Prelude as Stream
125-- >>> import qualified Streamly.Internal.Data.Stream.IsStream as Stream
126-- >>> import qualified Streamly.Internal.Data.Unfold as Unfold
127-- >>> import Control.Concurrent (threadDelay)
128-- >>> import System.IO (stdout, hSetBuffering, BufferMode(LineBuffering))
130-- >>> hSetBuffering stdout LineBuffering
132------------------------------------------------------------------------------
134------------------------------------------------------------------------------
136-- | Convert an 'Unfold' into a stream by supplying it an input seed.
138-- >>> Stream.drain $ Stream.unfold (Unfold.replicateM 3) (putStrLn "hello")
145unfold :: (IsStream t, Monad m) => Unfold m a b -> a -> t m b
146unfold unf x = fromStreamD $ D.unfold unf x
148-- | Convert an 'Unfold' with a closed input end into a stream.
151{-# INLINE unfold0 #-}
152unfold0 :: (IsStream t, Monad m) => Unfold m Void b -> t m b
153unfold0 unf = unfold unf (error "unfold0: unexpected void evaluation")
155------------------------------------------------------------------------------
156-- Generation by Unfolding
157------------------------------------------------------------------------------
163-- Nothing -> Stream.nil
164-- Just (a, b) -> a `Stream.cons` unfoldr step b
167-- Build a stream by unfolding a /pure/ step function @step@ starting from a
168-- seed @s@. The step function returns the next element in the stream and the
169-- next seed value. When it is done it returns 'Nothing' and the stream ends.
176-- else Just (b, b + 1)
177-- in Stream.toList $ Stream.unfoldr f 0
182{-# INLINE_EARLY unfoldr #-}
183unfoldr :: (Monad m, IsStream t) => (b -> Maybe (a, b)) -> b -> t m a
184unfoldr step seed = fromStreamD (D.unfoldr step seed)
185{-# RULES "unfoldr fallback to StreamK" [1]
186 forall a b. D.toStreamK (D.unfoldr a b) = K.unfoldr a b #-}
188-- | Build a stream by unfolding a /monadic/ step function starting from a
189-- seed. The step function returns the next element in the stream and the next
190-- seed value. When it is done it returns 'Nothing' and the stream ends. For
196-- then return Nothing
197-- else return (Just (b, b + 1))
198-- in Stream.toList $ Stream.unfoldrM f 0
202-- When run concurrently, the next unfold step can run concurrently with the
203-- processing of the output of the previous step. Note that more than one step
204-- cannot run concurrently as the next step depends on the output of the
210-- then return Nothing
211-- else threadDelay 1000000 >> return (Just (b, b + 1))
212-- in Stream.toList $ Stream.delay 1 $ Stream.fromAsync $ Stream.unfoldrM f 0
219{-# INLINE_EARLY unfoldrM #-}
220unfoldrM :: forall t m b a. (IsStream t, MonadAsync m) =>
221 (b -> m (Maybe (a, b))) -> b -> t m a
222unfoldrM step = fromStream . K.unfoldrMWith (IsStream.toConsK (consM @t)) step
224{-# RULES "unfoldrM serial" unfoldrM = unfoldrMSerial #-}
225{-# INLINE_EARLY unfoldrMSerial #-}
226unfoldrMSerial :: MonadAsync m => (b -> m (Maybe (a, b))) -> b -> SerialT m a
227unfoldrMSerial = Serial.unfoldrM
229{-# RULES "unfoldrM wSerial" unfoldrM = unfoldrMWSerial #-}
230{-# INLINE_EARLY unfoldrMWSerial #-}
231unfoldrMWSerial :: MonadAsync m => (b -> m (Maybe (a, b))) -> b -> WSerialT m a
232unfoldrMWSerial f = fromSerial . Serial.unfoldrM f
234{-# RULES "unfoldrM zipSerial" unfoldrM = unfoldrMZipSerial #-}
235{-# INLINE_EARLY unfoldrMZipSerial #-}
236unfoldrMZipSerial :: MonadAsync m =>
237 (b -> m (Maybe (a, b))) -> b -> ZipSerialM m a
238unfoldrMZipSerial f = fromSerial . Serial.unfoldrM f
240------------------------------------------------------------------------------
242------------------------------------------------------------------------------
245-- Generate an infinite stream by repeating a pure value.
248{-# INLINE_NORMAL repeat #-}
249repeat :: (IsStream t, Monad m) => a -> t m a
250repeat = fromStreamD . D.repeat
253-- >>> replicate n = Stream.take n . Stream.repeat
255-- Generate a stream of length @n@ by repeating a value @n@ times.
258{-# INLINE_NORMAL replicate #-}
259replicate :: (IsStream t, Monad m) => Int -> a -> t m a
260replicate n = fromStreamD . D.replicate n
263-- >>> replicateM n = Stream.take n . Stream.repeatM
265-- Generate a stream by performing a monadic action @n@ times. Same as:
267-- >>> pr n = threadDelay 1000000 >> print n
269-- This runs serially and takes 3 seconds:
271-- >>> Stream.drain $ Stream.fromSerial $ Stream.replicateM 3 $ pr 1
276-- This runs concurrently and takes just 1 second:
278-- >>> Stream.drain $ Stream.fromAsync $ Stream.replicateM 3 $ pr 1
286{-# INLINE_EARLY replicateM #-}
287replicateM :: forall t m a. (IsStream t, MonadAsync m) => Int -> m a -> t m a
289 fromStream . K.replicateMWith (IsStream.toConsK (consM @t)) count
291{-# RULES "replicateM serial" replicateM = replicateMSerial #-}
292{-# INLINE replicateMSerial #-}
293replicateMSerial :: MonadAsync m => Int -> m a -> SerialT m a
294replicateMSerial n = fromStreamD . D.replicateM n
296------------------------------------------------------------------------------
298------------------------------------------------------------------------------
300-- | @times@ returns a stream of time value tuples with clock of 10 ms
301-- granularity. The first component of the tuple is an absolute time reference
302-- (epoch) denoting the start of the stream and the second component is a time
303-- relative to the reference.
305-- >>> Stream.mapM_ (\x -> print x >> threadDelay 1000000) $ Stream.take 3 $ Stream.times
306-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),RelTime64 (NanoSecond64 ...))
307-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),RelTime64 (NanoSecond64 ...))
308-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),RelTime64 (NanoSecond64 ...))
310-- Note: This API is not safe on 32-bit machines.
315times :: (IsStream t, MonadAsync m) => t m (AbsTime, RelTime64)
316times = timesWith 0.01
318-- | @absTimes@ returns a stream of absolute timestamps using a clock of 10 ms
321-- >>> Stream.mapM_ print $ Stream.delayPre 1 $ Stream.take 3 $ Stream.absTimes
322-- AbsTime (TimeSpec {sec = ..., nsec = ...})
323-- AbsTime (TimeSpec {sec = ..., nsec = ...})
324-- AbsTime (TimeSpec {sec = ..., nsec = ...})
326-- Note: This API is not safe on 32-bit machines.
330{-# INLINE absTimes #-}
331absTimes :: (IsStream t, MonadAsync m, Functor (t m)) => t m AbsTime
332absTimes = fmap (uncurry addToAbsTime64) times
334{-# DEPRECATED currentTime "Please use absTimes instead" #-}
335{-# INLINE currentTime #-}
336currentTime :: (IsStream t, MonadAsync m, Functor (t m))
337 => Double -> t m AbsTime
338currentTime = absTimesWith
340-- | @relTimes@ returns a stream of relative time values starting from 0,
341-- using a clock of granularity 10 ms.
343-- >>> Stream.mapM_ print $ Stream.delayPre 1 $ Stream.take 3 $ Stream.relTimes
344-- RelTime64 (NanoSecond64 ...)
345-- RelTime64 (NanoSecond64 ...)
346-- RelTime64 (NanoSecond64 ...)
348-- Note: This API is not safe on 32-bit machines.
352{-# INLINE relTimes #-}
353relTimes :: (IsStream t, MonadAsync m, Functor (t m)) => t m RelTime64
354relTimes = fmap snd times
356-- | @durations g@ returns a stream of relative time values measuring the time
357-- elapsed since the immediate predecessor element of the stream was generated.
358-- The first element of the stream is always 0. @durations@ uses a clock of
359-- granularity @g@ specified in seconds. A low granularity clock is more
360-- expensive in terms of CPU usage. The minimum granularity is 1 millisecond.
361-- Durations lower than 1 ms will be 0.
363-- Note: This API is not safe on 32-bit machines.
367{-# INLINE durations #-}
368durations :: -- (IsStream t, MonadAsync m) =>
369 Double -> t m RelTime64
372-- | Generate ticks at the specified rate. The rate is adaptive, the tick
373-- generation speed can be increased or decreased at different times to achieve
374-- the specified rate. The specific behavior for different styles of 'Rate'
375-- specifications is documented under 'Rate'. The effective maximum rate
376-- achieved by a stream is governed by the processor speed.
381ticks :: -- (IsStream t, MonadAsync m) =>
385-- | Generate a singleton event at or after the specified absolute time. Note
386-- that this is different from a threadDelay, a threadDelay starts from the
387-- time when the action is evaluated, whereas if we use AbsTime based timeout
388-- it will immediately expire if the action is evaluated too late.
392{-# INLINE timeout #-}
393timeout :: -- (IsStream t, MonadAsync m) =>
397------------------------------------------------------------------------------
398-- From Generator functions
399------------------------------------------------------------------------------
401-- XXX we can remove it and recommend the definition in terms of enumerate and
402-- map. Check performance equivalence.
405-- >>> fromIndices f = fmap f $ Stream.enumerateFrom 0
406-- >>> fromIndices f = let g i = f i `Stream.cons` g (i + 1) in g 0
408-- Generate an infinite stream, whose values are the output of a function @f@
409-- applied on the corresponding index. Index starts at 0.
411-- >>> Stream.toList $ Stream.take 5 $ Stream.fromIndices id
415{-# INLINE fromIndices #-}
416fromIndices :: (IsStream t, Monad m) => (Int -> a) -> t m a
417fromIndices = fromStreamD . D.fromIndices
421-- >>> fromIndicesM f = Stream.mapM f $ Stream.enumerateFrom 0
422-- >>> fromIndicesM f = let g i = f i `Stream.consM` g (i + 1) in g 0
424-- Generate an infinite stream, whose values are the output of a monadic
425-- function @f@ applied on the corresponding index. Index starts at 0.
430{-# INLINE_EARLY fromIndicesM #-}
431fromIndicesM :: forall t m a. (IsStream t, MonadAsync m) =>
432 (Int -> m a) -> t m a
433fromIndicesM = fromStream . K.fromIndicesMWith (IsStream.toConsK (consM @t))
435{-# RULES "fromIndicesM serial" fromIndicesM = fromIndicesMSerial #-}
436{-# INLINE fromIndicesMSerial #-}
437fromIndicesMSerial :: MonadAsync m => (Int -> m a) -> SerialT m a
438fromIndicesMSerial = fromStreamD . D.fromIndicesM
440------------------------------------------------------------------------------
441-- Iterating functions
442------------------------------------------------------------------------------
445-- >>> iterate f x = x `Stream.cons` iterate f x
447-- Generate an infinite stream with @x@ as the first element and each
448-- successive element derived by applying the function @f@ on the previous
451-- >>> Stream.toList $ Stream.take 5 $ Stream.iterate (+1) 1
455{-# INLINE_NORMAL iterate #-}
456iterate :: (IsStream t, Monad m) => (a -> a) -> a -> t m a
457iterate step = fromStreamD . D.iterate step
460-- >>> iterateM f m = m >>= \a -> return a `Stream.consM` iterateM f (f a)
462-- Generate an infinite stream with the first element generated by the action
463-- @m@ and each successive element derived by applying the monadic function
464-- @f@ on the previous element.
466-- >>> pr n = threadDelay 1000000 >> print n
468-- Stream.iterateM (\x -> pr x >> return (x + 1)) (return 0)
470-- & Stream.fromSerial
477-- When run concurrently, the next iteration can run concurrently with the
478-- processing of the previous iteration. Note that more than one iteration
479-- cannot run concurrently as the next iteration depends on the output of the
480-- previous iteration.
483-- Stream.iterateM (\x -> pr x >> return (x + 1)) (return 0)
497-- /Since: 0.7.0 (signature change)/
498{-# INLINE_EARLY iterateM #-}
499iterateM :: forall t m a. (IsStream t, MonadAsync m) =>
500 (a -> m a) -> m a -> t m a
501iterateM f = fromStream . K.iterateMWith (IsStream.toConsK (consM @t)) f
503{-# RULES "iterateM serial" iterateM = iterateMSerial #-}
504{-# INLINE iterateMSerial #-}
505iterateMSerial :: MonadAsync m => (a -> m a) -> m a -> SerialT m a
506iterateMSerial step = fromStreamD . D.iterateM step
508-- | We can define cyclic structures using @let@:
510-- >>> let (a, b) = ([1, b], head a) in (a, b)
513-- The function @fix@ defined as:
515-- >>> fix f = let x = f x in x
517-- ensures that the argument of a function and its output refer to the same
518-- lazy value @x@ i.e. the same location in memory. Thus @x@ can be defined
519-- in terms of itself, creating structures with cyclic references.
521-- >>> f ~(a, b) = ([1, b], head a)
525-- 'Control.Monad.mfix' is essentially the same as @fix@ but for monadic
528-- Using 'mfix' for streams we can construct a stream in which each element of
529-- the stream is defined in a cyclic fashion. The argument of the function
530-- being fixed represents the current element of the stream which is being
531-- returned by the stream monad. Thus, we can use the argument to construct
534-- In the following example, the argument @action@ of the function @f@
535-- represents the tuple @(x,y)@ returned by it in a given iteration. We define
536-- the first element of the tuple in terms of the second.
538-- >>> import Streamly.Internal.Data.Stream.IsStream as Stream
539-- >>> import System.IO.Unsafe (unsafeInterleaveIO)
542-- main = Stream.mapM_ print $ Stream.mfix f
545-- let incr n act = fmap ((+n) . snd) $ unsafeInterleaveIO act
546-- x <- Stream.fromListM [incr 1 action, incr 2 action]
547-- y <- Stream.fromList [4,5]
551-- Note: you cannot achieve this by just changing the order of the monad
552-- statements because that would change the order in which the stream elements
555-- Note that the function @f@ must be lazy in its argument, that's why we use
556-- 'unsafeInterleaveIO' on @action@ because IO monad is strict.
560mfix :: (IsStream t, Monad m) => (m a -> t m a) -> t m a
561mfix f = fromStream $ K.mfix (toStream . f)
563------------------------------------------------------------------------------
565------------------------------------------------------------------------------
568-- >>> fromFoldable = Prelude.foldr Stream.cons Stream.nil
570-- Construct a stream from a 'Foldable' containing pure values:
573{-# INLINE fromFoldable #-}
574fromFoldable :: (IsStream t, Foldable f) => f a -> t m a
575fromFoldable = fromStream . K.fromFoldable
578-- >>> fromFoldableM = Prelude.foldr Stream.consM Stream.nil
580-- Construct a stream from a 'Foldable' containing monadic actions.
582-- >>> pr n = threadDelay 1000000 >> print n
583-- >>> Stream.drain $ Stream.fromSerial $ Stream.fromFoldableM $ map pr [1,2,3]
588-- >>> Stream.drain $ Stream.fromAsync $ Stream.fromFoldableM $ map pr [1,2,3]
593-- /Concurrent (do not use with 'fromParallel' on infinite containers)/
596{-# INLINE fromFoldableM #-}
597fromFoldableM :: (IsStream t, MonadAsync m, Foldable f) => f (m a) -> t m a
598fromFoldableM = Prelude.foldr consM IsStream.nil
601-- >>> fromListM = Stream.fromFoldableM
602-- >>> fromListM = Stream.sequence . Stream.fromList
603-- >>> fromListM = Stream.mapM id . Stream.fromList
604-- >>> fromListM = Prelude.foldr Stream.consM Stream.nil
606-- Construct a stream from a list of monadic actions. This is more efficient
607-- than 'fromFoldableM' for serial streams.
610{-# INLINE_EARLY fromListM #-}
611fromListM :: (MonadAsync m, IsStream t) => [m a] -> t m a
612fromListM = fromFoldableM
613{-# RULES "fromListM fallback to StreamK" [1]
614 forall a. D.toStreamK (D.fromListM a) = K.fromFoldableM a #-}
616{-# RULES "fromListM serial" fromListM = fromListMSerial #-}
617{-# INLINE_EARLY fromListMSerial #-}
618fromListMSerial :: MonadAsync m => [m a] -> SerialT m a
619fromListMSerial = fromStreamD . D.fromListM
621-- | Read lines from an IO Handle into a stream of Strings.
624{-# DEPRECATED fromHandle
625 "Please use Streamly.FileSystem.Handle module (see the changelog)" #-}
626fromHandle :: (IsStream t, MonadIO m) => IO.Handle -> t m String
629 go = IsStream.mkStream $ \_ yld _ stp -> do
630 eof <- liftIO $ IO.hIsEOF h
634 str <- liftIO $ IO.hGetLine h
637-- XXX This should perhaps be moved to Parallel
639-- | Takes a callback setter function and provides it with a callback. The
640-- callback when invoked adds a value at the tail of the stream. Returns a
641-- stream of values generated by the callback.
645{-# INLINE fromCallback #-}
646fromCallback :: MonadAsync m => ((a -> m ()) -> m ()) -> SerialT m a
647fromCallback setCallback = concatM $ do
648 (callback, stream) <- Par.newCallbackStream
650 return $ Stream.fromStreamK stream
652-- | Construct a stream by reading an 'Unboxed' 'IORef' repeatedly.
656{-# INLINE fromPrimIORef #-}
657fromPrimIORef :: (IsStream t, MonadIO m, Unboxed a) => Unboxed.IORef a -> t m a
658fromPrimIORef = fromStreamD . Unboxed.toStreamD
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