on de31277 help sign in
560 lines 17 kB history raw
1{-# OPTIONS_GHC -Wno-orphans #-}
3-- |
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
9-- Portability : GHC
10--
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
19 (
20 -- * Primitives
21 K.nil
22 , K.nilM
23 , K.cons
24 , (K..:)
26 , consM
27 , (|:)
29 -- * From 'Unfold'
30 , unfold
31 , unfold0
33 -- * Unfolding
34 , unfoldr
35 , unfoldrM
37 -- * From Values
38 , yield
39 , yieldM
40 , repeat
41 , repeatM
42 , replicate
43 , replicateM
45 -- * Enumeration
46 , Enumerable (..)
47 , enumerate
48 , enumerateTo
50 -- * Time Enumeration
51 , times
52 , absTimes
53 , absTimesWith
54 , relTimes
55 , relTimesWith
56 , durations
57 , ticks
58 , timeout
60 -- * From Generators
61 , fromIndices
62 , fromIndicesM
63 -- , generate
64 -- , generateM
66 -- * Iteration
67 , iterate
68 , iterateM
70 -- * Cyclic Elements
71 , K.mfix
73 -- * From Containers
74 , P.fromList
75 , fromListM
76 , K.fromFoldable
77 , fromFoldableM
78 , fromCallback
80 -- * Deprecated
81 , K.once
82 , each
83 , fromHandle
84 , currentTime
85 )
86where
88#include "inline.hs"
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
112#else
113import qualified Streamly.Internal.Data.Stream.StreamD.Generate as S
114#endif
115import qualified System.IO as IO
117import Prelude hiding (iterate, replicate, repeat)
119------------------------------------------------------------------------------
120-- From Unfold
121------------------------------------------------------------------------------
123-- | Convert an 'Unfold' into a stream by supplying it an input seed.
124--
125-- >>> unfold (UF.replicateM 10) (putStrLn "hello")
126--
127-- /Since: 0.7.0/
128{-# INLINE unfold #-}
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.
133--
134-- /Internal/
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------------------------------------------------------------------------------
143-- |
144-- @
145-- unfoldr step s =
146-- case step s of
147-- Nothing -> 'K.nil'
148-- Just (a, b) -> a \`cons` unfoldr step b
149-- @
150--
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.
154-- For example,
155--
156-- @
157-- let f b =
158-- if b > 3
159-- then Nothing
160-- else Just (b, b + 1)
161-- in toList $ unfoldr f 0
162-- @
163-- @
164-- [0,1,2,3]
165-- @
166--
167-- @since 0.1.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
177-- example,
178--
179-- @
180-- let f b =
181-- if b > 3
182-- then return Nothing
183-- else print b >> return (Just (b, b + 1))
184-- in drain $ unfoldrM f 0
185-- @
186-- @
187-- 0
188-- 1
189-- 2
190-- 3
191-- @
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
195-- previous step.
196--
197-- @
198-- (asyncly $ S.unfoldrM (\\n -> liftIO (threadDelay 1000000) >> return (Just (n, n + 1))) 0)
199-- & S.foldlM' (\\_ a -> threadDelay 1000000 >> print a) ()
200-- @
201--
202-- /Concurrent/
203--
204-- /Since: 0.1.0/
205{-# INLINE_EARLY unfoldrM #-}
206unfoldrM :: (IsStream t, MonadAsync m) => (b -> m (Maybe (a, b))) -> b -> t m a
207unfoldrM = K.unfoldrM
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------------------------------------------------------------------------------
225-- From Values
226------------------------------------------------------------------------------
228-- |
229-- Generate an infinite stream by repeating a pure value.
230--
231-- @since 0.4.0
232{-# INLINE_NORMAL repeat #-}
233repeat :: (IsStream t, Monad m) => a -> t m a
234repeat = fromStreamS . S.repeat
236-- |
237-- @
238-- replicate = take n . repeat
239-- @
240--
241-- Generate a stream of length @n@ by repeating a value @n@ times.
242--
243-- @since 0.6.0
244{-# INLINE_NORMAL replicate #-}
245replicate :: (IsStream t, Monad m) => Int -> a -> t m a
246replicate n = fromStreamS . S.replicate n
248-- |
249-- @
250-- replicateM = take n . repeatM
251-- @
252--
253-- Generate a stream by performing a monadic action @n@ times. Same as:
254--
255-- @
256-- drain $ serially $ S.replicateM 10 $ (threadDelay 1000000 >> print 1)
257-- drain $ asyncly $ S.replicateM 10 $ (threadDelay 1000000 >> print 1)
258-- @
259--
260-- /Concurrent/
261--
262-- @since 0.1.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------------------------------------------------------------------------------
273-- Time Enumeration
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.
280--
281-- @
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))
286-- @
287--
288-- Note: This API is not safe on 32-bit machines.
289--
290-- /Internal/
291--
292{-# INLINE times #-}
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
297-- granularity.
298--
299-- @
300-- >>> S.mapM_ print $ S.delayPre 1 $ S.absTimes
301-- @
302--
303-- Note: This API is not safe on 32-bit machines.
304--
305-- /Internal/
306--
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.
319--
320-- @
321-- >>> S.mapM_ print $ S.delayPre 1 $ S.relTimes
322-- @
323--
324-- Note: This API is not safe on 32-bit machines.
325--
326-- /Internal/
327--
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.
338--
339-- Note: This API is not safe on 32-bit machines.
340--
341-- /Unimplemented/
342--
343{-# INLINE durations #-}
344durations :: -- (IsStream t, MonadAsync m) =>
345 Double -> t m RelTime64
346durations = undefined
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.
353--
354-- /Unimplemented/
355--
356{-# INLINE ticks #-}
357ticks :: -- (IsStream t, MonadAsync m) =>
358 Rate -> t m ()
359ticks = undefined
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.
365--
366-- /Unimplemented/
367--
368{-# INLINE timeout #-}
369timeout :: -- (IsStream t, MonadAsync m) =>
370 AbsTime -> t m ()
371timeout = undefined
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.
379--
380-- |
381-- @
382-- fromIndices f = fmap f $ Stream.enumerateFrom 0
383-- fromIndices f = let g i = f i \`cons` g (i + 1) in g 0
384-- @
385--
386-- Generate an infinite stream, whose values are the output of a function @f@
387-- applied on the corresponding index. Index starts at 0.
388--
389-- @
390-- > Stream.toList $ Stream.take 5 $ Stream.fromIndices id
391-- [0,1,2,3,4]
392-- @
393--
394-- @since 0.6.0
395{-# INLINE fromIndices #-}
396fromIndices :: (IsStream t, Monad m) => (Int -> a) -> t m a
397fromIndices = fromStreamS . S.fromIndices
399--
400-- |
401-- @
402-- fromIndicesM f = Stream.mapM f $ Stream.enumerateFrom 0
403-- fromIndicesM f = let g i = f i \`consM` g (i + 1) in g 0
404-- @
405--
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.
408--
409-- /Concurrent/
410--
411-- @since 0.6.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------------------------------------------------------------------------------
425-- |
426-- @
427-- iterate f x = x \`cons` iterate f x
428-- @
429--
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
432-- element.
433--
434-- @
435-- > S.toList $ S.take 5 $ S.iterate (+1) 1
436-- [1,2,3,4,5]
437-- @
438--
439-- @since 0.1.2
440{-# INLINE_NORMAL iterate #-}
441iterate :: (IsStream t, Monad m) => (a -> a) -> a -> t m a
442iterate step = fromStreamS . S.iterate step
444-- |
445-- @
446-- iterateM f m = m >>= \a -> return a \`consM` iterateM f (f a)
447-- @
448--
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.
452--
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.
457--
458-- @
459-- drain $ serially $ S.take 10 $ S.iterateM
460-- (\\x -> threadDelay 1000000 >> print x >> return (x + 1)) (return 0)
461--
462-- drain $ asyncly $ S.take 10 $ S.iterateM
463-- (\\x -> threadDelay 1000000 >> print x >> return (x + 1)) (return 0)
464-- @
465--
466-- /Concurrent/
467--
468-- /Since: 0.1.2/
469--
470-- /Since: 0.7.0 (signature change)/
471{-# INLINE_EARLY iterateM #-}
472iterateM :: (IsStream t, MonadAsync m) => (a -> m a) -> m a -> t m a
473iterateM = K.iterateM
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------------------------------------------------------------------------------
481-- Conversions
482------------------------------------------------------------------------------
484-- |
485-- @
486-- fromFoldableM = 'Prelude.foldr' 'consM' 'K.nil'
487-- @
488--
489-- Construct a stream from a 'Foldable' containing monadic actions.
490--
491-- @
492-- drain $ serially $ S.fromFoldableM $ replicateM 10 (threadDelay 1000000 >> print 1)
493-- drain $ asyncly $ S.fromFoldableM $ replicateM 10 (threadDelay 1000000 >> print 1)
494-- @
495--
496-- /Concurrent (do not use with 'parallely' on infinite containers)/
497--
498-- @since 0.3.0
499{-# INLINE fromFoldableM #-}
500fromFoldableM :: (IsStream t, MonadAsync m, Foldable f) => f (m a) -> t m a
501fromFoldableM = Prelude.foldr consM K.nil
503-- |
504-- @
505-- fromListM = 'Prelude.foldr' 'K.consM' 'K.nil'
506-- @
507--
508-- Construct a stream from a list of monadic actions. This is more efficient
509-- than 'fromFoldableM' for serial streams.
510--
511-- @since 0.4.0
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'.
524--
525-- @since 0.1.0
526{-# DEPRECATED each "Please use fromFoldable instead." #-}
527{-# INLINE each #-}
528each :: (IsStream t, Foldable f) => f a -> t m a
529each = K.fromFoldable
531-- | Read lines from an IO Handle into a stream of Strings.
532--
533-- @since 0.1.0
534{-# DEPRECATED fromHandle
535 "Please use Streamly.FileSystem.Handle module (see the changelog)" #-}
536fromHandle :: (IsStream t, MonadIO m) => IO.Handle -> t m String
537fromHandle h = go
538 where
539 go = K.mkStream $ \_ yld _ stp -> do
540 eof <- liftIO $ IO.hIsEOF h
541 if eof
542 then stp
543 else do
544 str <- liftIO $ IO.hGetLine h
545 yld str go
547-- XXX This should perhaps be moved to Parallel
548--
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.
552--
553-- /Internal/
554--
555{-# INLINE fromCallback #-}
556fromCallback :: MonadAsync m => ((a -> m ()) -> m ()) -> SerialT m a
557fromCallback setCallback = concatM $ do
558 (callback, stream) <- Par.newCallbackStream
559 setCallback callback
560 return stream