on 03218ad help sign in
568 lines 19 kB history raw
1{-# OPTIONS_GHC -Wno-orphans #-}
3-- |
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
9-- Portability : GHC
10--
11-- Bottom level IsStream module that can be used by all other upper level
12-- IsStream modules.
14module Streamly.Internal.Data.Stream.IsStream.Common
15 (
16 -- * Generation
17 fromPure
18 , fromEffect
19 , repeatM
20 , timesWith
21 , absTimesWith
22 , relTimesWith
24 -- * Elimination
25 , fold
26 , fold_
28 -- * Transformation
29 , scanlMAfter'
30 , postscanlM'
31 , smapM
32 -- $smapM_Notes
33 , take
34 , takeWhile
35 , drop
36 , findIndices
37 , intersperseM
38 , interjectSuffix
39 , reverse
40 , reverse'
42 -- * Nesting
43 , concatM
44 , concatMapM
45 , concatMap
46 , splitOnSeq
48 -- * Deprecated
49 , yield
50 , yieldM
51 )
52where
54#include "inline.hs"
56import Control.Concurrent (threadDelay)
57import Control.Monad.IO.Class (MonadIO(..))
58import Foreign.Storable (Storable)
59import Streamly.Internal.Data.Array.Foreign.Type (Array)
60import Streamly.Internal.Data.Fold.Type (Fold (..))
61import Streamly.Internal.Data.Stream.IsStream.Combinators (maxYields)
62import Streamly.Internal.Data.Stream.Prelude (fromStreamS, toStreamS)
63import Streamly.Internal.Data.Stream.Serial (SerialT)
64import Streamly.Internal.Data.Stream.StreamD.Type (fromStreamD, toStreamD)
65import Streamly.Internal.Data.Stream.StreamK.Type (IsStream())
66import Streamly.Internal.Data.SVar (MonadAsync)
67import Streamly.Internal.Data.Time.Units (AbsTime, RelTime64, addToAbsTime64)
69import qualified Streamly.Internal.Data.Stream.Parallel as Par
70import qualified Streamly.Internal.Data.Stream.Serial as Serial
71import qualified Streamly.Internal.Data.Stream.StreamK as K (repeatM)
72import qualified Streamly.Internal.Data.Stream.StreamK.Type as K
73import qualified Streamly.Internal.Data.Stream.StreamD as D
74#ifdef USE_STREAMK_ONLY
75import qualified Streamly.Internal.Data.Stream.StreamK as S
76#else
77import qualified Streamly.Internal.Data.Stream.StreamD as S
78#endif
80import Prelude hiding (take, takeWhile, drop, reverse, concatMap)
82--
83-- $setup
84-- >>> :m
85-- >>> import Prelude hiding (take, takeWhile, drop, reverse)
86-- >>> import qualified Streamly.Prelude as Stream
87-- >>> import Streamly.Internal.Data.Stream.IsStream as Stream
88-- >>> import qualified Streamly.Data.Fold as Fold
89-- >>> import qualified Streamly.Data.Array.Foreign as Array
91------------------------------------------------------------------------------
92-- Generation
93------------------------------------------------------------------------------
95-- Faster than fromEffect because there is no bind.
96--
97-- |
98-- @
99-- fromPure a = a \`cons` nil
100-- @
101--
102-- Create a singleton stream from a pure value.
103--
104-- The following holds in monadic streams, but not in Zip streams:
105--
106-- @
107-- fromPure = pure
108-- fromPure = fromEffect . pure
109-- @
110--
111-- In Zip applicative streams 'fromPure' is not the same as 'pure' because in that
112-- case 'pure' is equivalent to 'repeat' instead. 'fromPure' and 'pure' are
113-- equally efficient, in other cases 'fromPure' may be slightly more efficient
114-- than the other equivalent definitions.
115--
116-- /Since: 0.8.0 (Renamed yield to fromPure)/
117--
118{-# INLINE fromPure #-}
119fromPure :: IsStream t => a -> t m a
120fromPure = K.fromPure
122-- | Same as 'fromPure'
123--
124-- @since 0.4.0
125{-# DEPRECATED yield "Please use fromPure instead." #-}
126{-# INLINE yield #-}
127yield :: IsStream t => a -> t m a
128yield = fromPure
130-- |
131-- @
132-- fromEffect m = m \`consM` nil
133-- @
134--
135-- Create a singleton stream from a monadic action.
136--
137-- @
138-- > Stream.toList $ Stream.fromEffect getLine
139-- hello
140-- ["hello"]
141-- @
142--
143-- /Since: 0.8.0 (Renamed yieldM to fromEffect)/
144--
145{-# INLINE fromEffect #-}
146fromEffect :: (Monad m, IsStream t) => m a -> t m a
147fromEffect = K.fromEffect
149-- | Same as 'fromEffect'
150--
151-- @since 0.4.0
152{-# DEPRECATED yieldM "Please use fromEffect instead." #-}
153{-# INLINE yieldM #-}
154yieldM :: (Monad m, IsStream t) => m a -> t m a
155yieldM = fromEffect
156-- |
157-- @
158-- repeatM = fix . consM
159-- repeatM = cycle1 . fromEffect
160-- @
161--
162-- Generate a stream by repeatedly executing a monadic action forever.
163--
164-- @
165-- drain $ fromSerial $ S.take 10 $ S.repeatM $ (threadDelay 1000000 >> print 1)
166-- drain $ fromAsync $ S.take 10 $ S.repeatM $ (threadDelay 1000000 >> print 1)
167-- @
168--
169-- /Concurrent, infinite (do not use with 'fromParallel')/
170--
171-- @since 0.2.0
172{-# INLINE_EARLY repeatM #-}
173repeatM :: (IsStream t, MonadAsync m) => m a -> t m a
174repeatM = K.repeatM
176{-# RULES "repeatM serial" repeatM = repeatMSerial #-}
177{-# INLINE repeatMSerial #-}
178repeatMSerial :: MonadAsync m => m a -> SerialT m a
179repeatMSerial = fromStreamS . S.repeatM
181------------------------------------------------------------------------------
182-- Generation - Time related
183------------------------------------------------------------------------------
185-- | @timesWith g@ returns a stream of time value tuples. The first component
186-- of the tuple is an absolute time reference (epoch) denoting the start of the
187-- stream and the second component is a time relative to the reference.
188--
189-- The argument @g@ specifies the granularity of the relative time in seconds.
190-- A lower granularity clock gives higher precision but is more expensive in
191-- terms of CPU usage. Any granularity lower than 1 ms is treated as 1 ms.
192--
193-- >>> import Control.Concurrent (threadDelay)
194-- >>> import Streamly.Internal.Data.Stream.IsStream.Common as Stream (timesWith)
195-- >>> Stream.mapM_ (\x -> print x >> threadDelay 1000000) $ Stream.take 3 $ Stream.timesWith 0.01
196-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),RelTime64 (NanoSecond64 ...))
197-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),RelTime64 (NanoSecond64 ...))
198-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),RelTime64 (NanoSecond64 ...))
199--
200-- Note: This API is not safe on 32-bit machines.
201--
202-- /Pre-release/
203--
204{-# INLINE timesWith #-}
205timesWith :: (IsStream t, MonadAsync m) => Double -> t m (AbsTime, RelTime64)
206timesWith g = fromStreamD $ D.times g
208-- | @absTimesWith g@ returns a stream of absolute timestamps using a clock of
209-- granularity @g@ specified in seconds. A low granularity clock is more
210-- expensive in terms of CPU usage. Any granularity lower than 1 ms is treated
211-- as 1 ms.
212--
213-- >>> Stream.mapM_ print $ Stream.delayPre 1 $ Stream.take 3 $ absTimesWith 0.01
214-- AbsTime (TimeSpec {sec = ..., nsec = ...})
215-- AbsTime (TimeSpec {sec = ..., nsec = ...})
216-- AbsTime (TimeSpec {sec = ..., nsec = ...})
217--
218-- Note: This API is not safe on 32-bit machines.
219--
220-- /Pre-release/
221--
222{-# INLINE absTimesWith #-}
223absTimesWith :: (IsStream t, MonadAsync m, Functor (t m))
224 => Double -> t m AbsTime
225absTimesWith = fmap (uncurry addToAbsTime64) . timesWith
227-- | @relTimesWith g@ returns a stream of relative time values starting from 0,
228-- using a clock of granularity @g@ specified in seconds. A low granularity
229-- clock is more expensive in terms of CPU usage. Any granularity lower than 1
230-- ms is treated as 1 ms.
231--
232-- >>> Stream.mapM_ print $ Stream.delayPre 1 $ Stream.take 3 $ Stream.relTimesWith 0.01
233-- RelTime64 (NanoSecond64 ...)
234-- RelTime64 (NanoSecond64 ...)
235-- RelTime64 (NanoSecond64 ...)
236--
237-- Note: This API is not safe on 32-bit machines.
238--
239-- /Pre-release/
240--
241{-# INLINE relTimesWith #-}
242relTimesWith :: (IsStream t, MonadAsync m, Functor (t m))
243 => Double -> t m RelTime64
244relTimesWith = fmap snd . timesWith
246------------------------------------------------------------------------------
247-- Elimination - Running a Fold
248------------------------------------------------------------------------------
250-- | Fold a stream using the supplied left 'Fold' and reducing the resulting
251-- expression strictly at each step. The behavior is similar to 'foldl''. A
252-- 'Fold' can terminate early without consuming the full stream. See the
253-- documentation of individual 'Fold's for termination behavior.
254--
255-- >>> Stream.fold Fold.sum (Stream.enumerateFromTo 1 100)
256-- 5050
257--
258-- Folds never fail, therefore, they produce a default value even when no input
259-- is provided. It means we can always fold an empty stream and get a valid
260-- result. For example:
261--
262-- >>> Stream.fold Fold.sum Stream.nil
263-- 0
264--
265-- However, 'foldMany' on an empty stream results in an empty stream.
266-- Therefore, @Stream.fold f@ is not the same as @Stream.head . Stream.foldMany
267-- f@.
268--
269-- @fold f = Stream.parse (Parser.fromFold f)@
270--
271-- @since 0.7.0
272{-# INLINE fold #-}
273fold :: Monad m => Fold m a b -> SerialT m a -> m b
274fold fl strm = do
275 (b, _) <- fold_ fl strm
276 return $! b
278{-# INLINE fold_ #-}
279fold_ :: Monad m => Fold m a b -> SerialT m a -> m (b, SerialT m a)
280fold_ fl strm = do
281 (b, str) <- D.fold_ fl $ D.toStreamD strm
282 return $! (b, D.fromStreamD str)
284------------------------------------------------------------------------------
285-- Transformation
286------------------------------------------------------------------------------
288-- | @scanlMAfter' accumulate initial done stream@ is like 'scanlM'' except
289-- that it provides an additional @done@ function to be applied on the
290-- accumulator when the stream stops. The result of @done@ is also emitted in
291-- the stream.
292--
293-- This function can be used to allocate a resource in the beginning of the
294-- scan and release it when the stream ends or to flush the internal state of
295-- the scan at the end.
296--
297-- /Pre-release/
298--
299{-# INLINE scanlMAfter' #-}
300scanlMAfter' :: (IsStream t, Monad m)
301 => (b -> a -> m b) -> m b -> (b -> m b) -> t m a -> t m b
302scanlMAfter' step initial done stream =
303 fromStreamD $ D.scanlMAfter' step initial done $ toStreamD stream
305-- XXX this needs to be concurrent
306-- | Like 'postscanl'' but with a monadic step function and a monadic seed.
307--
308-- /Since: 0.7.0/
309--
310-- /Since: 0.8.0 (signature change)/
311{-# INLINE postscanlM' #-}
312postscanlM' :: (IsStream t, Monad m) => (b -> a -> m b) -> m b -> t m a -> t m b
313postscanlM' step z m = fromStreamD $ D.postscanlM' step z $ toStreamD m
315-- $smapM_Notes
316--
317-- The stateful step function can be simplified to @(s -> a -> m b)@ to provide
318-- a read-only environment. However, that would just be 'mapM'.
319--
320-- The initial action could be @m (s, Maybe b)@, and we can also add a final
321-- action @s -> m (Maybe b)@. This can be used to get pre/post scan like
322-- functionality and also to flush the state in the end like scanlMAfter'.
323-- We can also use it along with a fusible version of bracket to get
324-- scanlMAfter' like functionality. See issue #677.
325--
326-- This can be further generalized to a type similar to Fold/Parser, giving it
327-- filtering and parsing capability as well (this is in fact equivalent to
328-- parseMany):
329--
330-- smapM :: (s -> a -> m (Step s b)) -> m s -> t m a -> t m b
331--
333-- | A stateful 'mapM', equivalent to a left scan, more like mapAccumL.
334-- Hopefully, this is a better alternative to @scan@. Separation of state from
335-- the output makes it easier to think in terms of a shared state, and also
336-- makes it easier to keep the state fully strict and the output lazy.
337--
338-- See also: 'scanlM''
339--
340-- /Pre-release/
341--
342{-# INLINE smapM #-}
343smapM :: (IsStream t, Monad m) =>
344 (s -> a -> m (s, b))
345 -> m s
346 -> t m a
347 -> t m b
348smapM step initial stream =
349 -- XXX implement this directly instead of using scanlM'
350 -- Once we have postscanlM' with monadic initial we can use this code
351 -- let r = postscanlM'
352 -- (\(s, _) a -> step s a)
353 -- (fmap (,undefined) initial)
354 -- stream
355 let r = postscanlM'
356 (\(s, _) a -> step s a)
357 (fmap (,undefined) initial)
358 stream
359 in Serial.map snd r
361------------------------------------------------------------------------------
362-- Transformation - Trimming
363------------------------------------------------------------------------------
365-- | Take first 'n' elements from the stream and discard the rest.
366--
367-- @since 0.1.0
368{-# INLINE take #-}
369take :: (IsStream t, Monad m) => Int -> t m a -> t m a
370take n m = fromStreamS $ S.take n $ toStreamS
371 (maxYields (Just (fromIntegral n)) m)
373-- | End the stream as soon as the predicate fails on an element.
374--
375-- @since 0.1.0
376{-# INLINE takeWhile #-}
377takeWhile :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m a
378takeWhile p m = fromStreamS $ S.takeWhile p $ toStreamS m
380-- | Discard first 'n' elements from the stream and take the rest.
381--
382-- @since 0.1.0
383{-# INLINE drop #-}
384drop :: (IsStream t, Monad m) => Int -> t m a -> t m a
385drop n m = fromStreamS $ S.drop n $ toStreamS m
387------------------------------------------------------------------------------
388-- Searching
389------------------------------------------------------------------------------
391-- | Find all the indices where the element in the stream satisfies the given
392-- predicate.
393--
394-- > findIndices = fold Fold.findIndices
395--
396-- @since 0.5.0
397{-# INLINE findIndices #-}
398findIndices :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m Int
399findIndices p m = fromStreamS $ S.findIndices p (toStreamS m)
401------------------------------------------------------------------------------
402-- Transformation by Inserting
403------------------------------------------------------------------------------
405-- intersperseM = intersperseBySpan 1
407-- | Insert an effect and its output before consuming an element of a stream
408-- except the first one.
409--
410-- >>> Stream.toList $ Stream.trace putChar $ Stream.intersperseM (putChar '.' >> return ',') $ Stream.fromList "hello"
411-- h.,e.,l.,l.,o"h,e,l,l,o"
412--
413-- @since 0.5.0
414{-# INLINE intersperseM #-}
415intersperseM :: (IsStream t, MonadAsync m) => m a -> t m a -> t m a
416intersperseM m = fromStreamS . S.intersperseM m . toStreamS
418-- | Intersperse a monadic action into the input stream after every @n@
419-- seconds.
420--
421-- @
422-- > import Control.Concurrent (threadDelay)
423-- > Stream.drain $ Stream.interjectSuffix 1 (putChar ',') $ Stream.mapM (\x -> threadDelay 1000000 >> putChar x) $ Stream.fromList "hello"
424-- h,e,l,l,o
425-- @
426--
427-- /Pre-release/
428{-# INLINE interjectSuffix #-}
429interjectSuffix
430 :: (IsStream t, MonadAsync m)
431 => Double -> m a -> t m a -> t m a
432interjectSuffix n f xs = xs `Par.parallelFst` repeatM timed
433 where timed = liftIO (threadDelay (round $ n * 1000000)) >> f
435------------------------------------------------------------------------------
436-- Transformation by Reordering
437------------------------------------------------------------------------------
439-- XXX Use a compact region list to temporarily store the list, in both reverse
440-- as well as in reverse'.
441--
442-- /Note:/ 'reverse'' is much faster than this, use that when performance
443-- matters.
444--
445-- > reverse = S.foldlT (flip S.cons) S.nil
446--
447-- | Returns the elements of the stream in reverse order. The stream must be
448-- finite. Note that this necessarily buffers the entire stream in memory.
449--
450-- /Since 0.7.0 (Monad m constraint)/
451--
452-- /Since: 0.1.1/
453{-# INLINE reverse #-}
454reverse :: (IsStream t, Monad m) => t m a -> t m a
455reverse s = fromStreamS $ S.reverse $ toStreamS s
457-- | Like 'reverse' but several times faster, requires a 'Storable' instance.
458--
459-- /Pre-release/
460{-# INLINE reverse' #-}
461reverse' :: (IsStream t, MonadIO m, Storable a) => t m a -> t m a
462reverse' s = fromStreamD $ D.reverse' $ toStreamD s
464------------------------------------------------------------------------------
465-- Combine streams and flatten
466------------------------------------------------------------------------------
468-- | Map a stream producing monadic function on each element of the stream
469-- and then flatten the results into a single stream. Since the stream
470-- generation function is monadic, unlike 'concatMap', it can produce an
471-- effect at the beginning of each iteration of the inner loop.
472--
473-- @since 0.6.0
474{-# INLINE concatMapM #-}
475concatMapM :: (IsStream t, Monad m) => (a -> m (t m b)) -> t m a -> t m b
476concatMapM f m = fromStreamD $ D.concatMapM (fmap toStreamD . f) (toStreamD m)
478-- | Map a stream producing function on each element of the stream and then
479-- flatten the results into a single stream.
480--
481-- @
482-- concatMap f = 'concatMapM' (return . f)
483-- concatMap = 'concatMapWith' 'Serial.serial'
484-- concatMap f = 'concat . map f'
485-- concatMap f = 'unfoldMany' (UF.lmap f UF.fromStream)
486-- @
487--
488-- @since 0.6.0
489{-# INLINE concatMap #-}
490concatMap ::(IsStream t, Monad m) => (a -> t m b) -> t m a -> t m b
491concatMap f m = fromStreamD $ D.concatMap (toStreamD . f) (toStreamD m)
493-- | Given a stream value in the underlying monad, lift and join the underlying
494-- monad with the stream monad.
495--
496-- @
497-- concatM = concat . fromEffect
498-- concatM = concat . lift -- requires @(MonadTrans t)@
499-- concatM = join . lift -- requires @(MonadTrans t@, @Monad (t m))@
500-- @
501--
502-- See also: 'concat', 'sequence'
503--
504-- /Internal/
505--
506{-# INLINE concatM #-}
507concatM :: (IsStream t, Monad m) => m (t m a) -> t m a
508concatM generator = concatMapM (\() -> generator) (fromPure ())
510------------------------------------------------------------------------------
511-- Split stream and fold
512------------------------------------------------------------------------------
514-- | Like 'splitOn' but the separator is a sequence of elements instead of a
515-- single element.
516--
517-- For illustration, let's define a function that operates on pure lists:
518--
519-- >>> splitOnSeq' pat xs = Stream.toList $ Stream.splitOnSeq (Array.fromList pat) Fold.toList (Stream.fromList xs)
520--
521-- >>> splitOnSeq' "" "hello"
522-- ["h","e","l","l","o"]
523--
524-- >>> splitOnSeq' "hello" ""
525-- [""]
526--
527-- >>> splitOnSeq' "hello" "hello"
528-- ["",""]
529--
530-- >>> splitOnSeq' "x" "hello"
531-- ["hello"]
532--
533-- >>> splitOnSeq' "h" "hello"
534-- ["","ello"]
535--
536-- >>> splitOnSeq' "o" "hello"
537-- ["hell",""]
538--
539-- >>> splitOnSeq' "e" "hello"
540-- ["h","llo"]
541--
542-- >>> splitOnSeq' "l" "hello"
543-- ["he","","o"]
544--
545-- >>> splitOnSeq' "ll" "hello"
546-- ["he","o"]
547--
548-- 'splitOnSeq' is an inverse of 'intercalate'. The following law always holds:
549--
550-- > intercalate . splitOn == id
551--
552-- The following law holds when the separator is non-empty and contains none of
553-- the elements present in the input lists:
554--
555-- > splitOn . intercalate == id
556--
557-- /Pre-release/
559-- XXX We can use a polymorphic vector implemented by Array# to represent the
560-- sequence, that way we can avoid the Storable constraint. If we still need
561-- Storable Array for performance, we can use a separate splitOnArray API for
562-- that. We can also have an API where the sequence itself is a lazy stream, so
563-- that we can search files in files for example.
564{-# INLINE splitOnSeq #-}
565splitOnSeq
566 :: (IsStream t, MonadIO m, Storable a, Enum a, Eq a)
567 => Array a -> Fold m a b -> t m a -> t m b
568splitOnSeq patt f m = D.fromStreamD $ D.splitOnSeq patt f (D.toStreamD m)