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
90import Control.Monad.IO.Class (MonadIO(..))
91import Data.Void (Void)
92import Streamly.Internal.Data.Unfold.Types (Unfold)
93import Streamly.Internal.Data.SVar (MonadAsync, Rate (..))
94import Streamly.Internal.Data.Stream.IsStream.Enumeration
95 (Enumerable(..), enumerate, enumerateTo)
96import Streamly.Internal.Data.Stream.IsStream.Common
97 (absTimesWith, concatM, relTimesWith, timesWith, yield, yieldM, repeatM)
98import Streamly.Internal.Data.Stream.Prelude (fromStreamS)
99import Streamly.Internal.Data.Stream.StreamD (fromStreamD)
100import Streamly.Internal.Data.Stream.StreamK (IsStream((|:), consM))
101import Streamly.Internal.Data.Stream.Serial (SerialT, WSerialT)
102import Streamly.Internal.Data.Stream.Zip (ZipSerialM)
103import Streamly.Internal.Data.Time.Units (AbsTime , RelTime64, addToAbsTime64)
105import qualified Streamly.Internal.Data.Stream.Parallel as Par
106import qualified Streamly.Internal.Data.Stream.Prelude as P
107import qualified Streamly.Internal.Data.Stream.Serial as Serial
108import qualified Streamly.Internal.Data.Stream.StreamD.Generate as D
109import qualified Streamly.Internal.Data.Stream.StreamK as K
110#ifdef USE_STREAMK_ONLY
111import qualified Streamly.Internal.Data.Stream.StreamK as S
113import qualified Streamly.Internal.Data.Stream.StreamD.Generate as S
115import qualified System.IO as IO
117import Prelude hiding (iterate, replicate, repeat)
119------------------------------------------------------------------------------
121------------------------------------------------------------------------------
123-- | Convert an 'Unfold' into a stream by supplying it an input seed.
125-- >>> unfold (UF.replicateM 10) (putStrLn "hello")
129unfold :: (IsStream t, Monad m) => Unfold m a b -> a -> t m b
130unfold unf x = fromStreamD $ D.unfold unf x
132-- | Convert an 'Unfold' with a closed input end into a stream.
135{-# INLINE unfold0 #-}
136unfold0 :: (IsStream t, Monad m) => Unfold m Void b -> t m b
137unfold0 unf = unfold unf (error "unfold0: unexpected void evaluation")
139------------------------------------------------------------------------------
140-- Generation by Unfolding
141------------------------------------------------------------------------------
148-- Just (a, b) -> a \`cons` unfoldr step b
151-- Build a stream by unfolding a /pure/ step function @step@ starting from a
152-- seed @s@. The step function returns the next element in the stream and the
153-- next seed value. When it is done it returns 'Nothing' and the stream ends.
160-- else Just (b, b + 1)
161-- in toList $ unfoldr f 0
168{-# INLINE_EARLY unfoldr #-}
169unfoldr :: (Monad m, IsStream t) => (b -> Maybe (a, b)) -> b -> t m a
170unfoldr step seed = fromStreamS (S.unfoldr step seed)
171{-# RULES "unfoldr fallback to StreamK" [1]
172 forall a b. S.toStreamK (S.unfoldr a b) = K.unfoldr a b #-}
174-- | Build a stream by unfolding a /monadic/ step function starting from a
175-- seed. The step function returns the next element in the stream and the next
176-- seed value. When it is done it returns 'Nothing' and the stream ends. For
182-- then return Nothing
183-- else print b >> return (Just (b, b + 1))
184-- in drain $ unfoldrM f 0
192-- When run concurrently, the next unfold step can run concurrently with the
193-- processing of the output of the previous step. Note that more than one step
194-- cannot run concurrently as the next step depends on the output of the
198-- (asyncly $ S.unfoldrM (\\n -> liftIO (threadDelay 1000000) >> return (Just (n, n + 1))) 0)
199-- & S.foldlM' (\\_ a -> threadDelay 1000000 >> print a) ()
205{-# INLINE_EARLY unfoldrM #-}
206unfoldrM :: (IsStream t, MonadAsync m) => (b -> m (Maybe (a, b))) -> b -> t m a
209{-# RULES "unfoldrM serial" unfoldrM = unfoldrMSerial #-}
210{-# INLINE_EARLY unfoldrMSerial #-}
211unfoldrMSerial :: MonadAsync m => (b -> m (Maybe (a, b))) -> b -> SerialT m a
212unfoldrMSerial = Serial.unfoldrM
214{-# RULES "unfoldrM wSerial" unfoldrM = unfoldrMWSerial #-}
215{-# INLINE_EARLY unfoldrMWSerial #-}
216unfoldrMWSerial :: MonadAsync m => (b -> m (Maybe (a, b))) -> b -> WSerialT m a
217unfoldrMWSerial = Serial.unfoldrM
219{-# RULES "unfoldrM zipSerial" unfoldrM = unfoldrMZipSerial #-}
220{-# INLINE_EARLY unfoldrMZipSerial #-}
221unfoldrMZipSerial :: MonadAsync m => (b -> m (Maybe (a, b))) -> b -> ZipSerialM m a
222unfoldrMZipSerial = Serial.unfoldrM
224------------------------------------------------------------------------------
226------------------------------------------------------------------------------
229-- Generate an infinite stream by repeating a pure value.
232{-# INLINE_NORMAL repeat #-}
233repeat :: (IsStream t, Monad m) => a -> t m a
234repeat = fromStreamS . S.repeat
238-- replicate = take n . repeat
241-- Generate a stream of length @n@ by repeating a value @n@ times.
244{-# INLINE_NORMAL replicate #-}
245replicate :: (IsStream t, Monad m) => Int -> a -> t m a
246replicate n = fromStreamS . S.replicate n
250-- replicateM = take n . repeatM
253-- Generate a stream by performing a monadic action @n@ times. Same as:
256-- drain $ serially $ S.replicateM 10 $ (threadDelay 1000000 >> print 1)
257-- drain $ asyncly $ S.replicateM 10 $ (threadDelay 1000000 >> print 1)
263{-# INLINE_EARLY replicateM #-}
264replicateM :: (IsStream t, MonadAsync m) => Int -> m a -> t m a
265replicateM = K.replicateM
267{-# RULES "replicateM serial" replicateM = replicateMSerial #-}
268{-# INLINE replicateMSerial #-}
269replicateMSerial :: MonadAsync m => Int -> m a -> SerialT m a
270replicateMSerial n = fromStreamS . S.replicateM n
272------------------------------------------------------------------------------
274------------------------------------------------------------------------------
276-- | @times@ returns a stream of time value tuples with clock of 10 ms
277-- granularity. The first component of the tuple is an absolute time reference
278-- (epoch) denoting the start of the stream and the second component is a time
279-- relative to the reference.
282-- >>> S.mapM_ (\x -> print x >> threadDelay 1000000) $ S.times
283-- > (AbsTime (TimeSpec {sec = 2496295, nsec = 536223000}),RelTime64 (NanoSecond64 0))
284-- > (AbsTime (TimeSpec {sec = 2496295, nsec = 536223000}),RelTime64 (NanoSecond64 1002028000))
285-- > (AbsTime (TimeSpec {sec = 2496295, nsec = 536223000}),RelTime64 (NanoSecond64 1996656000))
288-- Note: This API is not safe on 32-bit machines.
293times :: (IsStream t, MonadAsync m) => t m (AbsTime, RelTime64)
294times = timesWith 0.01
296-- | @absTimes@ returns a stream of absolute timestamps using a clock of 10 ms
300-- >>> S.mapM_ print $ S.delayPre 1 $ S.absTimes
303-- Note: This API is not safe on 32-bit machines.
307{-# INLINE absTimes #-}
308absTimes :: (IsStream t, MonadAsync m, Functor (t m)) => t m AbsTime
309absTimes = fmap (uncurry addToAbsTime64) times
311{-# DEPRECATED currentTime "Please use absTimes instead" #-}
312{-# INLINE currentTime #-}
313currentTime :: (IsStream t, MonadAsync m, Functor (t m))
314 => Double -> t m AbsTime
315currentTime = absTimesWith
317-- | @relTimes@ returns a stream of relative time values starting from 0,
318-- using a clock of granularity 10 ms.
321-- >>> S.mapM_ print $ S.delayPre 1 $ S.relTimes
324-- Note: This API is not safe on 32-bit machines.
328{-# INLINE relTimes #-}
329relTimes :: (IsStream t, MonadAsync m, Functor (t m)) => t m RelTime64
330relTimes = fmap snd times
332-- | @durations g@ returns a stream of relative time values measuring the time
333-- elapsed since the immediate predecessor element of the stream was generated.
334-- The first element of the stream is always 0. @durations@ uses a clock of
335-- granularity @g@ specified in seconds. A low granularity clock is more
336-- expensive in terms of CPU usage. The minimum granularity is 1 millisecond.
337-- Durations lower than 1 ms will be 0.
339-- Note: This API is not safe on 32-bit machines.
343{-# INLINE durations #-}
344durations :: -- (IsStream t, MonadAsync m) =>
345 Double -> t m RelTime64
348-- | Generate ticks at the specified rate. The rate is adaptive, the tick
349-- generation speed can be increased or decreased at different times to achieve
350-- the specified rate. The specific behavior for different styles of 'Rate'
351-- specifications is documented under 'Rate'. The effective maximum rate
352-- achieved by a stream is governed by the processor speed.
357ticks :: -- (IsStream t, MonadAsync m) =>
361-- | Generate a singleton event at or after the specified absolute time. Note
362-- that this is different from a threadDelay, a threadDelay starts from the
363-- time when the action is evaluated, whereas if we use AbsTime based timeout
364-- it will immediately expire if the action is evaluated too late.
368{-# INLINE timeout #-}
369timeout :: -- (IsStream t, MonadAsync m) =>
373------------------------------------------------------------------------------
374-- From Generator functions
375------------------------------------------------------------------------------
377-- XXX we can remove it and recommend the definition in terms of enumerate and
378-- map. Check performance equivalence.
382-- fromIndices f = fmap f $ Stream.enumerateFrom 0
383-- fromIndices f = let g i = f i \`cons` g (i + 1) in g 0
386-- Generate an infinite stream, whose values are the output of a function @f@
387-- applied on the corresponding index. Index starts at 0.
390-- > Stream.toList $ Stream.take 5 $ Stream.fromIndices id
395{-# INLINE fromIndices #-}
396fromIndices :: (IsStream t, Monad m) => (Int -> a) -> t m a
397fromIndices = fromStreamS . S.fromIndices
402-- fromIndicesM f = Stream.mapM f $ Stream.enumerateFrom 0
403-- fromIndicesM f = let g i = f i \`consM` g (i + 1) in g 0
406-- Generate an infinite stream, whose values are the output of a monadic
407-- function @f@ applied on the corresponding index. Index starts at 0.
412{-# INLINE_EARLY fromIndicesM #-}
413fromIndicesM :: (IsStream t, MonadAsync m) => (Int -> m a) -> t m a
414fromIndicesM = K.fromIndicesM
416{-# RULES "fromIndicesM serial" fromIndicesM = fromIndicesMSerial #-}
417{-# INLINE fromIndicesMSerial #-}
418fromIndicesMSerial :: MonadAsync m => (Int -> m a) -> SerialT m a
419fromIndicesMSerial = fromStreamS . S.fromIndicesM
421------------------------------------------------------------------------------
422-- Iterating functions
423------------------------------------------------------------------------------
427-- iterate f x = x \`cons` iterate f x
430-- Generate an infinite stream with @x@ as the first element and each
431-- successive element derived by applying the function @f@ on the previous
435-- > S.toList $ S.take 5 $ S.iterate (+1) 1
440{-# INLINE_NORMAL iterate #-}
441iterate :: (IsStream t, Monad m) => (a -> a) -> a -> t m a
442iterate step = fromStreamS . S.iterate step
446-- iterateM f m = m >>= \a -> return a \`consM` iterateM f (f a)
449-- Generate an infinite stream with the first element generated by the action
450-- @m@ and each successive element derived by applying the monadic function
451-- @f@ on the previous element.
453-- When run concurrently, the next iteration can run concurrently with the
454-- processing of the previous iteration. Note that more than one iteration
455-- cannot run concurrently as the next iteration depends on the output of the
456-- previous iteration.
459-- drain $ serially $ S.take 10 $ S.iterateM
460-- (\\x -> threadDelay 1000000 >> print x >> return (x + 1)) (return 0)
462-- drain $ asyncly $ S.take 10 $ S.iterateM
463-- (\\x -> threadDelay 1000000 >> print x >> return (x + 1)) (return 0)
470-- /Since: 0.7.0 (signature change)/
471{-# INLINE_EARLY iterateM #-}
472iterateM :: (IsStream t, MonadAsync m) => (a -> m a) -> m a -> t m a
475{-# RULES "iterateM serial" iterateM = iterateMSerial #-}
476{-# INLINE iterateMSerial #-}
477iterateMSerial :: MonadAsync m => (a -> m a) -> m a -> SerialT m a
478iterateMSerial step = fromStreamS . S.iterateM step
480------------------------------------------------------------------------------
482------------------------------------------------------------------------------
486-- fromFoldableM = 'Prelude.foldr' 'consM' 'K.nil'
489-- Construct a stream from a 'Foldable' containing monadic actions.
492-- drain $ serially $ S.fromFoldableM $ replicateM 10 (threadDelay 1000000 >> print 1)
493-- drain $ asyncly $ S.fromFoldableM $ replicateM 10 (threadDelay 1000000 >> print 1)
496-- /Concurrent (do not use with 'parallely' on infinite containers)/
499{-# INLINE fromFoldableM #-}
500fromFoldableM :: (IsStream t, MonadAsync m, Foldable f) => f (m a) -> t m a
501fromFoldableM = Prelude.foldr consM K.nil
505-- fromListM = 'Prelude.foldr' 'K.consM' 'K.nil'
508-- Construct a stream from a list of monadic actions. This is more efficient
509-- than 'fromFoldableM' for serial streams.
512{-# INLINE_EARLY fromListM #-}
513fromListM :: (MonadAsync m, IsStream t) => [m a] -> t m a
514fromListM = fromFoldableM
515{-# RULES "fromListM fallback to StreamK" [1]
516 forall a. D.toStreamK (D.fromListM a) = fromFoldableM a #-}
518{-# RULES "fromListM serial" fromListM = fromListMSerial #-}
519{-# INLINE_EARLY fromListMSerial #-}
520fromListMSerial :: MonadAsync m => [m a] -> SerialT m a
521fromListMSerial = fromStreamD . D.fromListM
523-- | Same as 'fromFoldable'.
526{-# DEPRECATED each "Please use fromFoldable instead." #-}
528each :: (IsStream t, Foldable f) => f a -> t m a
531-- | Read lines from an IO Handle into a stream of Strings.
534{-# DEPRECATED fromHandle
535 "Please use Streamly.FileSystem.Handle module (see the changelog)" #-}
536fromHandle :: (IsStream t, MonadIO m) => IO.Handle -> t m String
539 go = K.mkStream $ \_ yld _ stp -> do
540 eof <- liftIO $ IO.hIsEOF h
544 str <- liftIO $ IO.hGetLine h
547-- XXX This should perhaps be moved to Parallel
549-- | Takes a callback setter function and provides it with a callback. The
550-- callback when invoked adds a value at the tail of the stream. Returns a
551-- stream of values generated by the callback.
555{-# INLINE fromCallback #-}
556fromCallback :: MonadAsync m => ((a -> m ()) -> m ()) -> SerialT m a
557fromCallback setCallback = concatM $ do
558 (callback, stream) <- Par.newCallbackStream
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