3-- Copyright : (c) 2017 Harendra Kumar
6-- Maintainer : streamly@composewell.com
7-- Stability : experimental
10-- Streamly is a general purpose programming framework using cocnurrent data
11-- flow programming paradigm. It can be considered as a generalization of
12-- Haskell lists to monadic streaming with concurrent composition capability.
13-- The serial stream type in streamly @SerialT m a@ is like the list type @[a]@
14-- parameterized by the monad @m@. For example, @SerialT IO a@ is a moral
15-- equivalent of @[a]@ in the IO monad. Streams are constructed very much like
16-- lists, except that they use 'nil' and 'cons' instead of '[]' and ':'.
20-- > import "Streamly.Prelude" (cons, consM)
21-- > import qualified "Streamly.Prelude" as S
23-- > S.toList $ 1 \`cons` 2 \`cons` 3 \`cons` nil
27-- Unlike lists, streams can be constructed from monadic effects:
30-- > S.'toList' $ 'getLine' \`consM` 'getLine' \`consM` S.'nil'
36-- Streams are processed just like lists, with list like combinators, except
37-- that they are monadic and work in a streaming fashion. Here is a simple
38-- console echo program example:
41-- > S.drain $ S.repeatM getLine & S.mapM putStrLn
44-- @SerialT Identity a@ is a moral equivalent of pure lists. Streamly utilizes
45-- fusion for high performance, therefore, we can represent and process strings
46-- as streams of 'Char', encode and decode the streams to/from UTF8 and
47-- serialize them to @Array Word8@ obviating the need for special purpose
48-- libraries like @bytestring@ and @text@.
51-- please see the "Streamly.Tutorial" module and the examples directory in this
54{-# OPTIONS_GHC -Wno-orphans #-}
60 -- -- * Concepts Overview
76 -- * Stream transformers
77 -- | A stream represents a sequence of pure or effectful actions. The
78 -- `cons` and `consM` operations and the corresponding operators '.:' and
79 -- '|:' can be used to join pure values or effectful actions in a sequence.
80 -- The effects in the stream can be executed in many different ways
81 -- depending on the type of stream. In other words, the behavior of 'consM'
82 -- depends on the type of the stream.
84 -- There are three high level categories of streams, /spatially ordered/
85 -- streams, /speculative/ streams and /time ordered/ streams. Spatially
86 -- ordered streams, 'SerialT' and 'WSerialT', execute the effects in serial
87 -- order i.e. one at a time and present the outputs of those effects to the
88 -- consumer in the same order. Speculative streams, 'AheadT', may execute
89 -- many effects concurrently but present the outputs to the consumer in the
90 -- specified spatial order. Time ordered streams, 'AsyncT', 'WAsyncT' and
91 -- 'ParallelT', may execute many effects concurrently and present the
92 -- outputs of those effects to the consumer in time order i.e. as soon as
93 -- the output is generated.
95 -- We described above how the effects in a sequence are executed for
96 -- different types of streams. The behvavior of the 'Semigroup' and 'Monad'
97 -- instances follow the behavior of 'consM'. Stream generation operations
98 -- like 'repeatM' also execute the effects differently for different
99 -- streams, providing a concurrent generation capability when used with
100 -- stream types that execute effects concurrently. Similarly, effectful
101 -- transformation operations like 'mapM' also execute the transforming
102 -- effects differently for different types of streams.
109 -- ** Speculative Streams
113 -- ** Asynchronous Streams
119 -- ** Zipping Streams
124 -- * Parallel Function Application
141 -- * Concurrency Control
154 -- * Stream Type Adapters
178 -- ** Folding Containers of Streams
179 -- | These are variants of standard 'Foldable' fold functions that use a
180 -- polymorphic stream sum operation (e.g. 'async' or 'wSerial') to fold a
181 -- finite container of streams. Note that these are just special cases of
182 -- the more general 'concatMapWith' operation.
211 -- * Deprecated/Moved
212 -- | These APIs have been moved to other modules
220import Data.Semigroup (Semigroup(..))
221import Streamly.Internal.Data.SVar (MonadAsync, Rate(..))
222import Streamly.Internal.Data.Stream.Ahead
223import Streamly.Internal.Data.Stream.Async hiding (mkAsync)
224import Streamly.Internal.Data.Stream.Combinators
225import Streamly.Internal.Data.Stream.Parallel
226import Streamly.Internal.Data.Stream.Serial
227import Streamly.Internal.Data.Stream.StreamK hiding (serial)
228import Streamly.Internal.Data.Stream.Zip
230import qualified Streamly.Prelude as P
231import qualified Streamly.Internal.Data.Stream.IsStream as IP
232import qualified Streamly.Internal.Data.Stream.StreamK as K
233import qualified Streamly.Internal.Data.Stream.Async as Async
235-- XXX provide good succinct examples of pipelining, merging, splitting etc.
240-- A program is expressed as a network of streams and folds. A stream is a
241-- source or generator of data elements and a fold is a consumer of data elements that
242-- reduces multiple input elements to a single value.
244-- In the following example, a 'Word8' stream is generated by using
245-- 'Streamly.FileSystem.Handle.read' on a file handle, then the
246-- 'Streamly.Prelude.splitBySuffix' transformation splits the stream on
247-- newlines (ascii value 10); it uses the 'Streamly.Data.Fold.drain' fold to reduce
248-- the resulting lines to unit values (@()@), 'Streamly.Prelude.length' fold
249-- then counts the unit elements in the resulting stream which gives us the
250-- number of lines in the file:
252-- > S.length $ S.splitOnSuffix FL.drain 10 $ FH.read fh
254-- The following example folds the lines to arrays of 'Word8' using the
255-- 'Streamly.Memory.Array.writeF' fold and then wraps the lines in square
256-- brackets before writing them to standard output using
257-- 'Streamly.FileSystem.Handle.write':
259-- > wrapLine ln = S.fromList "[" <> A.read ln <> S.fromList "]\n"
260-- > readLines = S.splitOnSuffix A.writeF 10
261-- > FH.write stdout $ S.concatMap wrapLine $ readLines fh1
263-- One stream can be appended after another:
265-- > FH.write stdout $ S.concatMap wrapLine $ readLines fh1 <> readLines fh2
267-- The following example reads two files concurrently, merges the lines from
268-- the two streams and writes the resulting stream to another file:
270-- > FH.write stdout $ S.concatMap wrapLine $ readLines fh1 `parallel` readLines fh2
272-- There are many ways to generate, merge, zip, transform and fold data
273-- streams. Many transformations can be chained in a stream pipeline. See
274-- "Streamly.Prelude" module for combinators to manipulate streams.
278-- The way stream types in this module like 'SerialT' represent data sources,
279-- the same way the 'Fold' type from "Streamly.Data.Fold" represents data sinks or
280-- reducers of streams. Reducers can be combined to consume a stream source in
281-- many ways. The simplest is to reduce a stream source using a fold e.g.:
283-- > S.runFold FL.length $ S.enumerateTo 100
285-- Folds are consumers of streams and can be used to split a stream into
286-- multiple independent flows. Grouping transforms a stream by applying a fold
287-- on segments of a stream, distributing applies multiple folds in parallel on
288-- the same stream and combines them, partitioning sends different elements of
289-- a stream to different folds, unzipping divides the elements of a stream into
290-- parts and sends them through different folds. Parsers are nothing but a
291-- particular type of folds. Transformations can be applied contravariantly on
292-- the input of a fold.
296-- |---transform----Fold m a b--------|
297-- ---stream m a-->transform-->| |---f b c ...
298-- |---transform----Fold m a c--------|
306-- Streamly arrays (See "Streamly.Memory.Array") complement streams to provide an
307-- efficient computing paradigm. Streams are suitable for immutable
308-- transformations of /potentially infinite/ data using /sequential access/ and
309-- pipelined transformations whereas arrays are suitable for in-place
310-- transformations of /necessarily finite/ data using /random access/. Streams
311-- are synonymous with /sequential pipelined processing/ whereas arrays are
312-- synonymous with /efficient buffering and random access/.
314-- In general, a data processing pipeline reads data from some IO device, does
315-- some processing on it and finally writes the output to another IO device.
316-- Streams provide the overall framework of sequential processing pipeline in
317-- which arrays are used as buffering elements in the middle. In addition to
318-- buffering in the middle, arrays can also be used at the boundaries of the
319-- pipeline to efficiently interface with external storage systems like memory,
320-- files and network. If streams are the pipes in a water pipeline network
321-- then arrays are like the storage tanks in the middle. On the input side,
322-- think of arrays as buckets to fetch water to feed the pipeline and on the
323-- output side buckets to remove the processed water.
325-- 'ByteString' data type from the 'bytestring' package and the 'Text' data
326-- type from the 'text' package are special cases of arrays. 'ByteString' is
327-- like @Array Word8@ and 'Text' is like @utf16@ encoded @Array Word8@.
328-- Streamly arrays can be transformed as efficiently as @bytestring@ or @text@
329-- by using stream operations on them.
331-- Streams and arrays are equally important in computing. They are computing
332-- duals of each other.
335-- The basic stream type is 'Serial', it represents a sequence of IO actions,
336-- and is a 'Monad'. The type 'SerialT' is a monad transformer that can
337-- represent a sequence of actions in an arbitrary monad. The type 'Serial' is
338-- in fact a synonym for @SerialT IO@. There are a few more types similar to
339-- 'SerialT', all of them represent a stream and differ only in the
340-- 'Semigroup', 'Applicative' and 'Monad' compositions of the stream. 'Serial'
341-- and 'WSerial' types compose serially whereas 'Async' and 'WAsync'
342-- types compose concurrently. All these types can be freely inter-converted
343-- using type combinators without any cost. You can freely switch to any type
344-- of composition at any point in the program. When no type annotation or
345-- explicit stream type combinators are used, the default stream type is
346-- inferred as 'Serial'.
348-- This module exports stream types, instances and combinators for:
350-- * converting between different stream types
351-- * appending and concurrently merging streams
352-- * Concurrency control
353-- * Concurrent function application
354-- * Stream rate control
356-- This module is designed to be imported unqualified:
362-- See the "Streamly.Prelude" module for APIs for construction,
363-- generation, elimination and transformation of streams.
365------------------------------------------------------------------------------
366-- Eliminating a stream
367------------------------------------------------------------------------------
369-- | Same as 'runStream'
372{-# DEPRECATED runStreaming "Please use runStream instead." #-}
373runStreaming :: (Monad m, IsStream t) => t m a -> m ()
374runStreaming = P.drain . K.adapt
376-- | Same as @runStream@.
379{-# DEPRECATED runStreamT "Please use runStream instead." #-}
380runStreamT :: Monad m => SerialT m a -> m ()
383-- | Same as "Streamly.Prelude.runStream".
385{-# DEPRECATED runStream "Please use Streamly.Prelude.drain instead." #-}
386runStream :: Monad m => SerialT m a -> m ()
389-- | Same as @runStream . wSerially@.
392{-# DEPRECATED runInterleavedT "Please use 'runStream . interleaving' instead." #-}
393runInterleavedT :: Monad m => WSerialT m a -> m ()
394runInterleavedT = P.drain . K.adapt
396-- | Same as @runStream . parallely@.
399{-# DEPRECATED runParallelT "Please use 'runStream . parallely' instead." #-}
400runParallelT :: Monad m => ParallelT m a -> m ()
401runParallelT = P.drain . K.adapt
403-- | Same as @runStream . asyncly@.
406{-# DEPRECATED runAsyncT "Please use 'runStream . asyncly' instead." #-}
407runAsyncT :: Monad m => AsyncT m a -> m ()
408runAsyncT = P.drain . K.adapt
410-- | Same as @runStream . zipping@.
413{-# DEPRECATED runZipStream "Please use 'runStream . zipSerially instead." #-}
414runZipStream :: Monad m => ZipSerialM m a -> m ()
415runZipStream = P.drain . K.adapt
417-- | Same as @runStream . zippingAsync@.
420{-# DEPRECATED runZipAsync "Please use 'runStream . zipAsyncly instead." #-}
421runZipAsync :: Monad m => ZipAsyncM m a -> m ()
422runZipAsync = P.drain . K.adapt
425-- | Same as "Streamly.Prelude.foldWith".
427{-# DEPRECATED foldWith "Please use Streamly.Prelude.foldWith instead." #-}
428{-# INLINABLE foldWith #-}
429foldWith :: (IsStream t, Foldable f)
430 => (t m a -> t m a -> t m a) -> f (t m a) -> t m a
433-- | Same as "Streamly.Prelude.foldMapWith".
435{-# DEPRECATED foldMapWith "Please use Streamly.Prelude.foldMapWith instead." #-}
436{-# INLINABLE foldMapWith #-}
437foldMapWith :: (IsStream t, Foldable f)
438 => (t m b -> t m b -> t m b) -> (a -> t m b) -> f a -> t m b
439foldMapWith = P.foldMapWith
441-- | Same as "Streamly.Prelude.forEachWith".
443{-# DEPRECATED forEachWith "Please use Streamly.Prelude.forEachWith instead." #-}
444{-# INLINABLE forEachWith #-}
445forEachWith :: (IsStream t, Foldable f)
446 => (t m b -> t m b -> t m b) -> f a -> (a -> t m b) -> t m b
447forEachWith = P.forEachWith
450-- XXX Deprecate it in 0.8.0
452-- | Make a stream asynchronous, triggers the computation and returns a stream
453-- in the underlying monad representing the output generated by the original
454-- computation. The returned action is exhaustible and must be drained once. If
455-- not drained fully we may have a thread blocked forever and once exhausted it
456-- will always return 'empty'.
459{-# INLINABLE mkAsync #-}
460mkAsync :: (IsStream t, MonadAsync m) => t m a -> m (t m a)
461mkAsync = return . Async.mkAsync
463------------------------------------------------------------------------------
465------------------------------------------------------------------------------
469-- When a stream consumer demands an element from a serial stream constructed
470-- as @a \`consM` b \`consM` ... nil@, the action @a@ at the head of the stream
471-- sequence is executed and the result is supplied to the consumer. When the
472-- next element is demanded, the action @b@ is executed and its result is
473-- supplied. Thus, the effects are performed and results are consumed strictly
474-- in a serial order. Serial streams can be considered as /spatially ordered/
475-- streams as the order of execution and consumption is the same as the spatial
476-- order in which the actions are composed by the programmer.
478-- Serial streams enforce the side effects as well as the results of the
479-- actions to be in the same order in which the actions are added to the
480-- stream. Therefore, the semigroup operation for serial streams is not
484-- a <> b is not the same as b <> a
487-- There are two serial stream types 'SerialT' and 'WSerialT'. The stream
488-- evaluation of both the variants works in the same way as described above,
489-- they differ only in the 'Semigroup' and 'Monad' implementaitons.
493-- When a stream consumer demands an element from a speculative stream
494-- constructed as @a \`consM` b \`consM` ... nil@, the action @a@ at the head
495-- of the stream is executed and the output of the action is supplied to the
496-- consumer. However, in addition to the action at the head multiple actions
497-- following it may also be executed concurrently and the results buffered.
498-- When the next element is demanded it may be served from the buffer and we
499-- may execute the next action in the sequence to keep the buffer adequately
500-- filled. Thus, the actions are executed concurrently but results consumed in
501-- serial order just like serial streams. `consM` can be used to fold an
502-- infinite lazy container of effects, as the number of concurrent executions
505-- Similar to 'consM', the monadic stream generation (e.g. replicateM) and
506-- transformation operations (e.g. mapM) on speculative streams can execute
507-- multiple effects concurrently in a speculative manner.
509-- How many effects can be executed concurrently and how many results can be
510-- buffered are controlled by 'maxThreads' and 'maxBuffer' combinators
511-- respectively. The actual number of concurrent threads is adjusted according
512-- to the rate at which the consumer is consuming the stream. It may even
513-- execute actions serially in a single thread if that is enough to match the
516-- Speculative streams enforce ordering of the results of actions in the stream
517-- but the side effects are only partially ordered. Therefore, the semigroup
518-- operation for speculative streams is not commutative from the pure outputs
519-- perspective but commutative from side effects perspective.
523-- /Scheduling and execution:/ In an asynchronous stream @a \`consM` b \`consM`
524-- c ...@, the actions @a@, @b@, and @c@ are executed concurrently with the
525-- consumer of the stream. The actions are /scheduled/ for execution in the
526-- same order as they are specified in the stream. Multiple scheduled actions
527-- may be /executed/ concurrently in parallel threads of execution. The
528-- actions may be executed out of order and they may complete at arbitrary
529-- times. Therefore, the /effects/ of the actions may be observed out of
532-- /Buffering:/ The /results/ from multiple threads of execution are queued in
533-- a buffer as soon as they become available. The consumer of the stream is
534-- served from this buffer. Therefore, the consumer may observe the results to
535-- be out of order. In other words, an asynchronous stream is an unordered
536-- stream i.e. order does not matter.
538-- /Concurrency control:/ Threads are suspended if the `maxBuffer` limit is
539-- reached, and resumed when the consumer makes space in the buffer. The
540-- maximum number of concurrent threads depends on `maxThreads`. Number of
541-- threads is increased or decreased based on the speed of the consumer.
543-- /Generation operations:/ Concurrent stream generation operations e.g.
544-- 'Streamly.Prelude.replicateM' when used in async style schedule and execute
545-- the stream generating actions in the manner described above. The generation
546-- actions run concurrently, effects and results of the actions as observed by
547-- the consumer of the stream may be out of order.
549-- /Transformation operations:/ Concurrent stream transformation operations
550-- e.g. 'Streamly.Prelude.mapM', when used in async style, schedule and
551-- execute transformation actions in the manner described above. Transformation
552-- actions run concurrently, effects and results of the actions may be
553-- observed by the consumer out of order.
555-- /Variants:/ There are two asynchronous stream types 'AsyncT' and 'WAsyncT'.
556-- They are identical with respect to single stream evaluation behavior. Their
557-- behaviors differ in how they combine multiple streams using 'Semigroup' or
558-- 'Monad' composition. Since the order of elements does not matter in
559-- asynchronous streams the 'Semigroup' operation is effectively commutative.
563-- 'ZipSerialM' and 'ZipAsyncM', provide 'Applicative' instances for zipping the
564-- corresponding elements of two streams together. Note that these types are
569-- Stream processing functions can be composed in a chain using function
570-- application with or without the '$' operator, or with reverse function
571-- application operator '&'. Streamly provides concurrent versions of these
572-- operators applying stream processing functions such that each stage of the
573-- stream can run in parallel. The operators start with a @|@; we can read '|$'
574-- as "@parallel dollar@" to remember that @|@ comes before '$'.
576-- Imports for the code snippets below:
580-- import qualified Streamly.Prelude as S
581-- import Control.Concurrent
585-- The 'Semigroup' operation '<>' of each stream type combines two streams in a
586-- type specific manner. This section provides polymorphic versions of '<>'
587-- which can be used to combine two streams in a predetermined way irrespective
590-- XXX An alternative design choice would be to let a control parameter affect
591-- the nearest SVar only and then it gets cleared. The benefit of the current
592-- choice is that it is simply just like global configuration, just like state
593-- behaves, so should be easy to comprehend. But it has the downside of leaking
594-- to undesired actions, that is we can forget to reset it.
598-- These combinators can be used at any point in a stream composition to set
599-- parameters to control the concurrency of the /argument stream/. A control
600-- parameter set at any point remains effective for any concurrent combinators
601-- used in the argument stream until it is reset by using the combinator again.
602-- These control parameters have no effect on non-concurrent combinators in the
603-- stream, or on non-concurrent streams.
605-- /Pitfall:/ Remember that 'maxBuffer' in the following example applies to
606-- 'mapM' and any other combinators that may follow it, and it does not apply
607-- to the combinators before it:
616-- If we use '&' instead of '$' the situation will reverse, in the following
617-- example, 'maxBuffer' does not apply to 'mapM', it applies to combinators
618-- that come before it, because those are the arguments to 'maxBuffer':
629-- You may want to use different stream composition styles at different points
630-- in your program. Stream types can be freely converted or adapted from one
631-- type to another. The 'IsStream' type class facilitates type conversion of
632-- one stream type to another. It is not used directly, instead the type
633-- combinators provided below are used for conversions.
635-- To adapt from one monomorphic type (e.g. 'AsyncT') to another monomorphic
636-- type (e.g. 'SerialT') use the 'adapt' combinator. To give a polymorphic code
637-- a specific interpretation or to adapt a specific type to a polymorphic type
638-- use the type specific combinators e.g. 'asyncly' or 'wSerially'. You
639-- cannot adapt polymorphic code to polymorphic code, as the compiler would not know
640-- which specific type you are converting from or to. If you see a an
641-- @ambiguous type variable@ error then most likely you are using 'adapt'
642-- unnecessarily on polymorphic code.
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