on c1ba040 help sign in
streamly/src/Streamly/Tutorial.hs
1742 lines 64 kB history raw
1{-# OPTIONS_GHC -fno-warn-unused-imports #-}
2-- |
3-- Module : Streamly.Tutorial
4-- Copyright : (c) 2017 Harendra Kumar
5--
6-- License : BSD3
7-- Maintainer : harendra.kumar@gmail.com
8--
9-- Streamly is a general computing framework based on concurrent data flow
10-- programming. The IO monad and pure lists are a special case of streamly. On
11-- one hand, streamly extends the lists of pure values to lists of monadic
12-- actions, on the other hand it extends the IO monad with concurrent
13-- non-determinism. In simple imperative terms we can say that streamly extends
14-- the IO monad with @for@ loops and nested @for@ loops with concurrency
15-- support. Hopefully, this analogy becomes clearer once you go through this
16-- tutorial.
17--
18-- Streaming in general enables writing modular, composable and scalable
19-- applications with ease, and concurrency allows you to make them scale and
20-- perform well. Streamly enables writing scalable concurrent applications
21-- without being aware of threads or synchronization. No explicit thread
22-- control is needed. Where applicable, concurrency rate is automatically
23-- controlled based on the demand by the consumer. However, combinators can be
24-- used to fine tune the concurrency control.
25--
26-- Streaming and concurrency together enable expressing reactive applications
27-- conveniently. See the @CirclingSquare@ example in the examples directory for
28-- a simple SDL based FRP example. To summarize, streamly provides a unified
29-- computing framework for streaming, non-determinism and functional reactive
30-- programming in an elegant and simple API that is a natural extension of pure
31-- lists to monadic streams.
32--
33-- In this tutorial we will go over the basic concepts and how to use the
34-- library. Before you go through this tutorial we recommend that you take a
35-- look at:
36--
37-- * The quick overview in the package <README.md README file>.
38-- * The overview of streams and folds in the "Streamly" module.
39--
40-- Once you finish this tutorial, see the last section for further reading
41-- resources.
43module Streamly.Tutorial
44 (
45 -- * Stream Types
46 -- $streams
48 -- * Concurrent Streams
49 -- $concurrentStreams
51 -- * Combining Streams
52 -- $flavors
54 -- * Imports and Supporting Code
55 -- $imports
57 -- * Generating Streams
58 -- $generating
60 -- * Generating Streams Concurrently
61 -- $generatingConcurrently
63 -- * Eliminating Streams
64 -- $eliminating
66 -- * Concurrent Pipeline Stages
67 -- $concurrentApplication
69 -- * Transforming Streams
70 -- $transformation
72 -- * Mapping Concurrently
73 -- $concurrentTransformation
75 -- * Merging Streams
77 -- ** Semigroup Style
78 -- $semigroup
80 -- *** Deep Serial Composition ('Serial')
81 -- $serial
83 -- *** Wide Serial Composition ('WSerial')
84 -- $interleaved
86 -- *** Deep Speculative Composition ('Ahead')
87 -- $ahead
89 -- *** Deep Asynchronous Composition ('Async')
90 -- $async
92 -- *** Wide Asynchronous Composition ('WAsync')
93 -- $wasync
95 -- *** Parallel Asynchronous Composition ('Parallel')
96 -- $parallel
98 -- XXX we should deprecate and remove the mkAsync API
99 -- Custom composition
100 -- custom
102 -- ** Monoid Style
103 -- $monoid
105 -- * Nesting Streams
106 -- $nesting
108 -- ** Monad
109 -- $monad
111 -- *** Deep Serial Nesting ('Serial')
112 -- $regularSerial
114 -- *** Wide Serial Nesting ('WSerial')
115 -- $interleavedNesting
117 -- *** Deep Speculative Nesting ('Ahead')
118 -- $aheadNesting
120 -- *** Deep Asynchronous Nesting ('Async')
121 -- $concurrentNesting
123 -- *** Wide Asynchronous Nesting ('WAsync')
124 -- $wasyncNesting
126 -- *** Parallel Asynchronous Nesting ('Parallel')
127 -- $parallelNesting
129 -- *** Exercise
130 -- $monadExercise
132 -- ** Applicative
133 -- $applicative
135 -- ** Functor
136 -- $functor
138 -- * Zipping Streams
139 -- $zipping
141 -- ** Serial Zipping
142 -- $serialzip
144 -- ** Parallel Zipping
145 -- $parallelzip
147 -- * Monad transformers
148 -- $monadtransformers
150 -- * Concurrent Programming
151 -- $concurrent
153 -- * Reactive Programming
154 -- $reactive
156 -- * Writing Concurrent Programs
157 -- $programs
159 -- * Performance
160 -- $performance
162 -- * Interoperation with Streaming Libraries
163 -- $interop
165 -- * Comparison with Existing Packages
166 -- $comparison
168 -- * Where to go next?
169 -- $furtherReading
170 )
171where
173import Streamly hiding (foldWith, foldMapWith, forEachWith)
174import Streamly.Prelude
175import Data.Semigroup
176import Control.Applicative
177import Control.Monad
178import Control.Monad.IO.Class (MonadIO(..))
179import Control.Monad.Trans.Class (MonadTrans (lift))
181-- $streams
182--
183-- The monadic stream API offered by Streamly is very close to the Haskell
184-- "Prelude" pure lists' API, it can be considered as a natural extension of
185-- lists to monadic actions. Streamly streams provide concurrent composition
186-- and merging of streams. It can be considered as a concurrent list
187-- transformer.
188--
189-- The basic stream type is 'Serial', it represents a sequence of IO actions,
190-- and is a 'Monad'. The 'Serial' monad is almost a drop in replacement for
191-- the 'IO' monad, IO monad is a special case of the 'Serial' monad; IO monad
192-- represents a single IO action whereas the 'Serial' monad represents a series
193-- of IO actions. The only change you need to make to go from 'IO' to 'Serial'
194-- is to use 'drain' to run the monad and to prefix the IO actions with
195-- either 'yieldM' or 'liftIO'. If you use liftIO you can switch from 'Serial'
196-- to IO monad by simply removing the 'drain' function; no other changes
197-- are needed unless you have used some stream specific composition or
198-- combinators.
199--
200-- Similarly, the 'Serial' type is almost a drop in replacement for pure lists,
201-- pure lists are a special case of monadic streams. If you use 'nil' in place
202-- of '[]' and '|:' in place ':' you can replace a list with a 'Serial' stream.
203-- The only difference is that the elements must be monadic type and to operate
204-- on the streams we must use the corresponding functions from
205-- "Streamly.Prelude" instead of using the base "Prelude".
207-- $concurrentStreams
208--
209-- Many stream operations can be done concurrently:
210--
211-- * Streams can be generated concurrently.
212--
213-- * Streams can be merged concurrently.
214--
215-- * Multiple stages in a streaming pipeline can run concurrently.
216--
217-- * Streams can be mapped and zipped concurrently.
218--
219-- * In monadic composition they combine like a list transformer,
220-- providing concurrent non-determinism.
221--
222-- There are three basic concurrent stream styles, 'Ahead', 'Async', and
223-- 'Parallel'. The 'Ahead' style streams are similar to 'Serial' except that
224-- they can speculatively execute multiple stream actions concurrently in
225-- advance. 'Ahead' would return exactly the same stream as 'Serial' except
226-- that it may execute the actions concurrently. The 'Async' style streams,
227-- like 'Ahead', speculatively execute multiple stream actions in advance but
228-- return the results in their finishing order rather than in the stream
229-- traversal order. 'Parallel' is like 'Async' except that it provides
230-- unbounded parallelism instead of controlled parallelism.
231--
232-- For easy reference, we can classify the stream types based on /execution order/,
233-- /consumption order/, and /bounded or unbounded/ concurrency.
234-- Execution could be serial (i.e. synchronous) or asynchronous. In serial
235-- execution we execute the next action in the stream only after the previous
236-- one has finished executing. In asynchronous execution multiple actions in
237-- the stream can be executed asynchronously i.e. the next action can start
238-- executing even before the first one has finished. Consumption order
239-- determines the order in which the outputs generated by the composition are
240-- consumed. Consumption could be serial or asynchronous. In serial
241-- consumption, the outputs are consumed in the traversal order, in
242-- asynchronous consumption the outputs are consumed as they arrive i.e. first
243-- come first serve order.
244--
245-- +------------+--------------+--------------+--------------+
246-- | Type | Execution | Consumption | Concurrency |
247-- +============+==============+==============+==============+
248-- | 'Serial' | Serial | Serial | None |
249-- +------------+--------------+--------------+--------------+
250-- | 'Ahead' | Asynchronous | Serial | bounded |
251-- +------------+--------------+--------------+--------------+
252-- | 'Async' | Asynchronous | Asynchronous | bounded |
253-- +------------+--------------+--------------+--------------+
254-- | 'Parallel' | Asynchronous | Asynchronous | unbounded |
255-- +------------+--------------+--------------+--------------+
256--
257-- All these types can be freely inter-converted using type conversion
258-- combinators or type annotations, without any cost, to achieve the desired
259-- composition style. To force a particular type of composition, we coerce the
260-- stream type using the corresponding type adapting combinator from
261-- 'serially', 'aheadly', 'asyncly', or 'parallely'. The default stream type
262-- is inferred as 'Serial' unless you change it by using one of the combinators
263-- or by using a type annotation.
265-- $flavors
266--
267-- Streams can be combined using '<>' or 'mappend' to form a
268-- composite. Composite streams can be interpreted in a depth first or
269-- breadth first manner using an appropriate type conversion before
270-- consumption. Deep (e.g. 'Serial') stream type variants traverse a
271-- composite stream in a depth first manner, such that each stream is
272-- traversed fully before traversing the next stream. Wide
273-- (e.g. 'WSerial') stream types traverse it in a breadth first
274-- manner, such that one element from each stream is traversed before
275-- coming back to the first stream again.
276--
277-- Each stream type has a wide traversal variant prefixed by 'W'. The wide
278-- variant differs only in the Semigroup\/Monoid, Applicative\/Monad
279-- compositions of the streams.
280-- The following table summarizes the basic types and the corresponding wide
281-- variants:
282--
283-- @
284-- +------------+-----------+
285-- | Deep | Wide |
286-- +============+===========+
287-- | 'Serial' | 'WSerial' |
288-- +------------+-----------+
289-- | 'Ahead' | 'WAhead' |
290-- +------------+-----------+
291-- | 'Async' | 'WAsync' |
292-- +------------+-----------+
293-- @
294--
295-- Other than these types there are also 'ZipSerial' and 'ZipAsync' types that
296-- zip streams serially or concurrently using 'Applicative' operation. These
297-- types are not monads they are only applicatives and they do not differ in
298-- 'Semigroup' composition.
299--
301-- $programs
302--
303-- When writing concurrent programs it is advised to not use the concurrent
304-- style stream combinators blindly at the top level. That might create too
305-- much concurrency where it is not even required, and can even degrade
306-- performance in some cases. In some cases it can also lead to surprising
307-- behavior because of some code that is supposed to be serial becoming
308-- concurrent. Please be aware that all concurrency capable APIs that you may
309-- have used under the scope of a concurrent stream combinator will become
310-- concurrent. For example if you have a 'repeatM' somewhere in your program
311-- and you use 'parallely' on top, the 'repeatM' becomes fully parallel,
312-- resulting into an infinite parallel execution . Instead, use the
313-- /Keep It Serial and Stupid/ principle, start with the default serial
314-- composition and enable concurrent combinators only when and where necessary.
315-- When you use a concurrent combinator you can use an explicit 'serially'
316-- combinator to suppress any unnecessary concurrency under the scope of that
317-- combinator.
319-- $monadtransformers
320--
321-- To represent streams in an arbitrary monad use the more general monad
322-- transformer types for example the monad transformer type corresponding to
323-- the 'Serial' type is 'SerialT'. @SerialT m a@ represents a stream of values
324-- of type 'a' in some underlying monad 'm'. For example, @SerialT IO Int@ is a
325-- stream of 'Int' in 'IO' monad. In fact, the type 'Serial' is a synonym for
326-- @SerialT IO@.
327--
328-- Similarly we have monad transformer types for other stream types as well viz.
329-- 'WSerialT', 'AsyncT', 'WAsyncT' and 'ParallelT'.
330--
331-- To lift a value from an underlying monad in a monad transformer stack into a
332-- singleton stream use 'lift' and to lift from an IO action use 'liftIO'.
333--
334-- @
335-- > S.'drain' $ liftIO $ putStrLn "Hello world!"
336-- Hello world!
337-- > S.'drain' $ lift $ putStrLn "Hello world!"
338-- Hello world!
339-- @
340--
342-- $generating
343--
344-- We will assume the following imports in this tutorial. Go ahead, fire up a
345-- GHCi session and import these lines to start playing.
346--
347-- @
348-- > import "Streamly"
349-- > import "Streamly.Prelude" ((|:))
350-- > import qualified "Streamly.Prelude" as S
351--
352-- > import Control.Concurrent
353-- @
354--
355-- 'nil' represents an empty stream and 'consM' or its operator form '|:' adds
356-- a monadic action at the head of the stream.
357--
358-- @
359-- > S.'toList' S.'nil'
360-- []
361-- > S.'toList' $ 'getLine' |: 'getLine' |: S.'nil'
362-- hello
363-- world
364-- ["hello","world"]
365-- @
366--
367-- To create a singleton stream from a pure value use 'yield' or 'pure' and to
368-- create a singleton stream from a monadic action use 'yieldM'. Note that in
369-- case of Zip applicative streams "pure" repeats the value to generate an
370-- infinite stream.
371--
372-- @
373-- > S.'toList' $ 'pure' 1
374-- [1]
375-- > S.'toList' $ S.'yield' 1
376-- [1]
377-- > S.'toList' $ S.'yieldM' 'getLine'
378-- hello
379-- ["hello"]
380-- @
381--
382-- To create a stream from pure values in a 'Foldable' container use
383-- 'fromFoldable' which is equivalent to a fold using 'cons' and 'nil':
384--
385-- @
386-- > S.'toList' $ S.'fromFoldable' [1..3]
387-- [1,2,3]
388-- > S.'toList' $ 'Prelude.foldr' S.'cons' S.'nil' [1..3]
389-- [1,2,3]
390-- @
391--
392-- To create a stream from monadic actions in a 'Foldable' container just use a
393-- right fold using 'consM' and 'nil':
394--
395-- @
396-- > S.'drain' $ 'Prelude.foldr' ('|:') S.'nil' ['putStr' "Hello ", 'putStrLn' "world!"]
397-- Hello world!
398-- @
399--
400-- For more ways to construct a stream see the module "Streamly.Prelude".
402-- $generatingConcurrently
403--
404-- Monadic construction and generation functions like 'consM', 'unfoldrM',
405-- 'replicateM', 'repeatM', 'iterateM' and 'fromFoldableM' work concurrently
406-- when used with appropriate stream type combinator. The pure versions of
407-- these APIs are not concurrent, however you can use the monadic versions even
408-- for pure computations by wrapping the pure value in a monad to get the
409-- concurrent generation capability where required.
410--
411-- The following code finishes in 3 seconds (6 seconds when serial):
412--
413-- @
414-- > let p n = threadDelay (n * 1000000) >> return n
415-- > S.'toList' $ 'parallely' $ p 3 |: p 2 |: p 1 |: S.'nil'
416-- [1,2,3]
417-- > S.'toList' $ 'aheadly' $ p 3 |: p 2 |: p 1 |: S.'nil'
418-- [3,2,1]
419-- @
420-- The following finishes in 10 seconds (100 seconds when serial):
421--
422-- @
423-- > S.drain $ 'asyncly' $ S.'replicateM' 10 $ p 10
424-- @
425--
427-- $eliminating
428--
429-- We have already seen 'drain' and 'toList' to eliminate a stream in the
430-- examples above. 'drain' runs a stream discarding the results i.e. only
431-- for effects. 'toList' runs the stream and collects the results in a list.
432--
433-- For other ways to eliminate a stream see the @Folding@ section in
434-- "Streamly.Prelude" module.
436-- $transformation
437--
438-- Transformation over a stream is the equivalent of a @for@ loop construct in
439-- imperative paradigm. We iterate over every element in the stream and perform
440-- certain transformations for each element. Transformations may involve
441-- mapping functions over the elements, filtering elements from the stream or
442-- folding all the elements in the stream into a single value. Streamly streams
443-- are exactly like lists and you can perform all the transformations in the
444-- same way as you would on lists.
445--
446-- Here is a simple console echo program that just echoes every input line,
447-- forever:
448--
449-- @
450-- > import Data.Function ((&))
451-- > S.'drain' $ S.'repeatM' getLine & S.'mapM' putStrLn
452-- @
453--
454-- The following code snippet reads lines from standard input, filters blank
455-- lines, drops the first non-blank line, takes the next two, up cases them,
456-- numbers them and prints them:
457--
458-- @
459-- import "Streamly"
460-- import qualified "Streamly.Prelude" as S
461-- import Data.Char (toUpper)
462-- import Data.Function ((&))
463--
464-- main = S.'drain' $
465-- S.'repeatM' getLine
466-- & S.'filter' (not . null)
467-- & S.'drop' 1
468-- & S.'take' 2
469-- & fmap (map toUpper)
470-- & S.'zipWith' (\\n s -> show n ++ " " ++ s) (S.'fromFoldable' [1..])
471-- & S.'mapM' putStrLn
472-- @
474-- $concurrentTransformation
475--
476-- Monadic transformation functions 'mapM' and 'sequence' work concurrently
477-- when used with appropriate stream type combinators. The pure versions do not
478-- work concurrently, however you can use the monadic versions even for pure
479-- computations to get the concurrent transformation capability where required.
480--
481-- This would print a value every second (2 seconds when serial):
482--
483-- @
484-- > let p n = threadDelay (n * 1000000) >> return n
485-- > S.'drain' $ S.aheadly $ S.'mapM' (\\x -> p 1 >> print x) (serially $ S.repeatM (p 1))
486-- @
487--
489-- $concurrentApplication
490--
491-- The concurrent function application operators '|$' and '|&' apply a stream
492-- argument to a stream function concurrently to compose a concurrent pipeline
493-- of stream processing functions:
494--
495-- Because both the stages run concurrently, we would see a delay of only 1
496-- second instead of 2 seconds in the following:
497--
498-- @
499-- > let p n = threadDelay (n * 1000000) >> return n
500-- > S.'drain' $ S.'repeatM' (p 1) '|&' S.'mapM' (\\x -> p 1 >> print x)
501-- @
503-- $semigroup
504--
505-- We can combine two streams into a single stream using semigroup composition
506-- operation '<>'. Streams can be combined in many different ways as described
507-- in the following sections, the '<>' operation behaves differently depending
508-- on the stream type in effect. The stream type and therefore the composition
509-- style can be changed at any point using one of the type combinators as
510-- discussed earlier.
512-- $imports
513--
514-- In most of example snippets we do not repeat the imports. Where imports are
515-- not explicitly specified use the imports shown below.
516--
517-- @
518-- import "Streamly"
519-- import "Streamly.Prelude" ((|:), nil)
520-- import qualified "Streamly.Prelude" as S
521--
522-- import Control.Concurrent
523-- import Control.Monad (forever)
524-- @
525--
526-- To illustrate concurrent vs serial composition aspects, we will use the
527-- following @delay@ function to introduce a sleep or delay specified in
528-- seconds. After the delay it prints the number of seconds it slept.
529--
530-- @
531-- delay n = S.'yieldM' $ do
532-- threadDelay (n * 1000000)
533-- tid \<- myThreadId
534-- putStrLn (show tid ++ ": Delay " ++ show n)
535-- @
537-- $serial
538--
539-- The 'Semigroup' operation '<>' of the 'Serial' type combines the two streams
540-- in a /serial depth first/ manner. We use the 'serially' type combinator to
541-- effect 'Serial' style of composition. We can also use an explicit 'Serial'
542-- type annotation for the stream to achieve the same effect. However, since
543-- 'Serial' is the default type unless explicitly specified by using a
544-- combinator, we can omit using an explicit combinator or type annotation for
545-- this style of composition.
546--
547-- When two streams with multiple elements are combined in this manner, the
548-- monadic actions in the two streams are performed sequentially i.e. first all
549-- actions in the first stream are performed sequentially and then all actions
550-- in the second stream are performed sequentially. We call it
551-- /serial depth first/ as the full depth of one stream is fully traversed
552-- before we move to the next. The following example prints the sequence 1, 2,
553-- 3, 4:
554--
555-- @
556-- main = S.'drain' $ (print 1 |: print 2 |: nil) <> (print 3 |: print 4 |: nil)
557-- @
558-- @
559-- 1
560-- 2
561-- 3
562-- 4
563-- @
564--
565-- All actions in both the streams are performed serially in the same thread.
566-- In the following example we can see that all actions are performed in the
567-- same thread and take a combined total of @3 + 2 + 1 = 6@ seconds:
568--
569-- @
570-- main = S.'drain' $ delay 3 <> delay 2 <> delay 1
571-- @
572-- @
573-- ThreadId 36: Delay 3
574-- ThreadId 36: Delay 2
575-- ThreadId 36: Delay 1
576-- @
577--
578-- The polymorphic version of the binary operation '<>' of the 'Serial' type is
579-- 'serial'. We can use 'serial' to join streams in a sequential manner
580-- irrespective of the type of stream:
581--
582-- @
583-- main = S.'drain' $ (print 1 |: print 2 |: nil) \`serial` (print 3 |: print 4 |: nil)
584-- @
586-- $interleaved
587--
588-- The 'Semigroup' operation '<>' of the 'WSerial' type combines the two
589-- streams in a /serial breadth first/ manner. We use the 'wSerially' type
590-- combinator to effect 'WSerial' style of composition. We can also use the
591-- 'WSerial' type annotation for the stream to achieve the same effect.
592--
593-- When two streams with multiple elements are combined in this manner, we
594-- traverse all the streams in a breadth first manner i.e. one action from each
595-- stream is performed and yielded to the resulting stream before we come back
596-- to the first stream again and so on.
597-- The following example prints the sequence 1, 3, 2, 4
598--
599-- @
600-- main = S.'drain' . 'wSerially' $ (print 1 |: print 2 |: nil) <> (print 3 |: print 4 |: nil)
601-- @
602-- @
603-- 1
604-- 3
605-- 2
606-- 4
607-- @
608--
609-- Even though the monadic actions of the two streams are performed in an
610-- interleaved manner they are all performed serially in the same thread. In
611-- the following example we can see that all actions are performed in the same
612-- thread and take a combined total of @3 + 2 + 1 = 6@ seconds:
613--
614-- @
615-- main = S.'drain' . 'wSerially' $ delay 3 <> delay 2 <> delay 1
616-- @
617-- @
618-- ThreadId 36: Delay 3
619-- ThreadId 36: Delay 2
620-- ThreadId 36: Delay 1
621-- @
622--
623-- The polymorphic version of the 'WSerial' binary operation '<>' is called
624-- 'wSerial'. We can use 'wSerial' to join streams in an interleaved manner
625-- irrespective of the type, notice that we have not used the 'wSerially'
626-- combinator in the following example:
627--
628-- @
629-- main = S.'drain' $ (print 1 |: print 2 |: nil) \`wSerial` (print 3 |: print 4 |: nil)
630-- @
631-- @
632-- 1
633-- 3
634-- 2
635-- 4
636-- @
637--
638-- Note that this composition cannot be used to fold infinite number of streams
639-- since it requires preserving the state until a stream is finished.
641-- $ahead
642--
643-- The 'Semigroup' operation '<>' of the 'Ahead' type combines two streams in a
644-- /serial depth first/ manner with concurrent lookahead. We use the 'aheadly'
645-- type combinator to effect 'Ahead' style of composition. We can also use an
646-- explicit 'Ahead' type annotation for the stream to achieve the same effect.
647--
648-- When two streams are combined in this manner, the streams are traversed in
649-- depth first manner just like 'Serial', however it can execute the next
650-- stream concurrently and keep the results ready when its turn arrives.
651-- Concurrent execution of the next stream(s) is performed if the first stream
652-- blocks or if it cannot produce output at the rate that is enough to meet the
653-- consumer demand. Multiple streams can be executed concurrently to meet the
654-- demand. The following example would print the result in a second even
655-- though each action in each stream takes one second:
656--
657-- @
658-- main = do
659-- xs \<- S.'toList' . 'aheadly' $ (p 1 |: p 2 |: nil) <> (p 3 |: p 4 |: nil)
660-- print xs
661-- where p n = threadDelay 1000000 >> return n
662-- @
663-- @
664-- [1,2,3,4]
665-- @
666--
667-- Each stream is constructed 'aheadly' and then both the streams are merged
668-- 'aheadly', therefore, all the actions can run concurrently but the result is
669-- presented in serial order.
670--
671-- You can also use the polymorphic combinator 'ahead' in place of '<>' to
672-- compose any type of streams in this manner.
674-- $async
675--
676-- The 'Semigroup' operation '<>' of the 'Async' type combines the two
677-- streams in a depth first manner with parallel look ahead. We use the
678-- 'asyncly' type combinator to effect 'Async' style of composition. We
679-- can also use the 'Async' type annotation for the stream type to achieve
680-- the same effect.
681--
682-- When two streams with multiple elements are combined in this manner, the
683-- streams are traversed in depth first manner just like 'Serial', however it
684-- can execute the next stream concurrently and return the results from it
685-- as they arrive i.e. the results from the next stream may be yielded even
686-- before the results from the first stream. Concurrent execution of the next
687-- stream(s) is performed if the first stream blocks or if it cannot produce
688-- output at the rate that is enough to meet the consumer demand. Multiple
689-- streams can be executed concurrently to meet the demand.
690-- In the example below each element in the stream introduces a constant delay
691-- of 1 second, however, it takes just one second to produce all the results.
692-- The results are not guaranteed to be in any particular order:
693--
694-- @
695-- main = do
696-- xs \<- S.'toList' . 'asyncly' $ (p 1 |: p 2 |: nil) <> (p 3 |: p 4 |: nil)
697-- print xs
698-- where p n = threadDelay 1000000 >> return n
699-- @
700-- @
701-- [4,2,1,3]
702-- @
703--
704-- The constituent streams are also composed in 'Async' manner and the
705-- composition of streams too. We can compose the constituent streams to run
706-- serially, in that case it would take 2 seconds to produce all the results.
707-- The elements in the serial streams would be in serial order in the results:
708--
709-- @
710-- main = do
711-- xs \<- S.'toList' . 'asyncly' $ (serially $ p 1 |: p 2 |: nil) <> (serially $ p 3 |: p 4 |: nil)
712-- print xs
713-- where p n = threadDelay 1000000 >> return n
714-- @
715-- @
716-- [3,1,2,4]
717-- @
718--
719-- In the following example we can see that new threads are started when a
720-- computation blocks. Notice that the output from the stream with the
721-- shortest delay is printed first. The whole computation takes @maximum of
722-- (3, 2, 1) = 3@ seconds:
723--
724-- @
725-- main = S.'drain' . 'asyncly' $ delay 3 '<>' delay 2 '<>' delay 1
726-- @
727-- @
728-- ThreadId 42: Delay 1
729-- ThreadId 41: Delay 2
730-- ThreadId 40: Delay 3
731-- @
732--
733-- When we have a tree of computations composed using this style, the tree is
734-- traversed in DFS style just like the 'Serial' style, the only difference is
735-- that here we can move on to executing the next stream if a stream blocks.
736-- However, we will not start new threads if we have sufficient output to
737-- saturate the consumer. This is why we call it left-biased demand driven or
738-- adaptive concurrency style, the concurrency tends to stay on the left side
739-- of the composition as long as possible. More threads are started based on
740-- the pull rate of the consumer. The following example prints an output every
741-- second as all of the actions are concurrent.
742--
743-- @
744-- main = S.'drain' . 'asyncly' $ (delay 1 <> delay 2) <> (delay 3 <> delay 4)
745-- @
746-- @
747-- 1
748-- 2
749-- 3
750-- 4
751-- @
752--
753-- All the computations may even run in a single thread when more threads are
754-- not needed. As you can see, in the following example the computations are
755-- run in a single thread one after another, because none of them blocks.
756-- However, if the thread consuming the stream were faster than the producer
757-- then it would have started parallel threads for each computation to keep up
758-- even if none of them blocks:
759--
760-- @
761-- main = S.'drain' . 'asyncly' $ traced (sqrt 9) '<>' traced (sqrt 16) '<>' traced (sqrt 25)
762-- where traced m = S.'yieldM' (myThreadId >>= print) >> return m
763-- @
764-- @
765-- ThreadId 40
766-- ThreadId 40
767-- ThreadId 40
768-- @
769--
770-- Note that the order of printing in the above examples may change due to
771-- variations in scheduling latencies for concurrent threads.
772--
773-- The polymorphic version of the 'Async' binary operation '<>' is called
774-- 'async'. We can use 'async' to join streams in a left biased
775-- adaptively concurrent manner irrespective of the type, notice that we have
776-- not used the 'asyncly' combinator in the following example:
777--
778-- @
779-- main = S.'drain' $ delay 3 \`async` delay 2 \`async` delay 1
780-- @
781-- @
782-- ThreadId 42: Delay 1
783-- ThreadId 41: Delay 2
784-- ThreadId 40: Delay 3
785-- @
786--
787-- Since the concurrency provided by this operator is demand driven it cannot
788-- be used when the composed computations start timers that are relative to
789-- each other because all computations may not be started at the same time and
790-- therefore timers in all of them may not start at the same time. When
791-- relative timing among all computations is important or when we need to start
792-- all computations at once for any reason 'Parallel' style must be used
793-- instead.
794--
795-- 'Async' style utilizes resources optimally and should be preferred over
796-- 'Parallel' or 'WAsync' unless you really need those. 'Async' should be used
797-- when we know that the computations can run in parallel but we do not care if
798-- they actually run in parallel or not, that decision can be left to the
799-- scheduler based on demand. Also, note that 'async' operator can be used to fold
800-- infinite number of streams in contrast to the 'Parallel' or 'WAsync' styles,
801-- because it does not require us to run all of them at the same time in a fair
802-- manner.
804-- $wasync
805--
806-- The 'Semigroup' operation '<>' of the 'WAsync' type combines two streams in
807-- a concurrent manner using /breadth first traversal/. We use the 'wAsyncly'
808-- type combinator to effect 'WAsync' style of composition. We can also use the
809-- 'WAsync' type annotation for the stream to achieve the same effect.
810--
811-- When streams with multiple elements are combined in this manner, we traverse
812-- all the streams concurrently in a breadth first manner i.e. one action from
813-- each stream is performed and yielded to the resulting stream before we come
814-- back to the first stream again and so on. Even though we execute the actions
815-- in a breadth first order the outputs are consumed on a first come first
816-- serve basis.
817--
818-- In the following example we can see that outputs are produced in the breadth
819-- first traversal order but this is not guaranteed.
820--
821-- @
822-- main = S.'drain' . 'wAsyncly' $ (serially $ print 1 |: print 2 |: nil) <> (serially $ print 3 |: print 4 |: nil)
823-- @
824-- @
825-- 1
826-- 3
827-- 2
828-- 4
829-- @
830--
831-- The polymorphic version of the binary operation '<>' of the 'WAsync' type is
832-- 'wAsync'. We can use 'wAsync' to join streams using a breadth first
833-- concurrent traversal irrespective of the type, notice that we have not used
834-- the 'wAsyncly' combinator in the following example:
835--
836-- @
837-- main = S.'drain' $ delay 3 \`wAsync` delay 2 \`wAsync` delay 1
838-- @
839-- @
840-- ThreadId 42: Delay 1
841-- ThreadId 41: Delay 2
842-- ThreadId 40: Delay 3
843-- @
844--
845-- Since the concurrency provided by this style is demand driven it may not
846-- be used when the composed computations start timers that are relative to
847-- each other because all computations may not be started at the same time and
848-- therefore timers in all of them may not start at the same time. When
849-- relative timing among all computations is important or when we need to start
850-- all computations at once for any reason 'Parallel' style must be used
851-- instead.
852--
854-- $parallel
855--
856-- The 'Semigroup' operation '<>' of the 'Parallel' type combines the two
857-- streams in a fairly concurrent manner with round robin scheduling. We use
858-- the 'parallely' type combinator to effect 'Parallel' style of composition.
859-- We can also use the 'Parallel' type annotation for the stream type to
860-- achieve the same effect.
861--
862-- When two streams with multiple elements are combined in this manner, the
863-- monadic actions in both the streams are performed concurrently with a fair
864-- round robin scheduling. The outputs are yielded in the order in which the
865-- actions complete. This is pretty similar to the 'WAsync' type, the
866-- difference is that 'WAsync' is adaptive to the consumer demand and may or
867-- may not execute all actions in parallel depending on the demand, whereas
868-- 'Parallel' runs all the streams in parallel irrespective of the demand.
869--
870-- The following example sends a query to all the three search engines in
871-- parallel and prints the name of the search engines in the order in which the
872-- responses arrive. You need the [http-conduit](http://hackage.haskell.org/package/http-conduit)
873-- package to run this example:
874--
875-- @
876-- import "Streamly"
877-- import qualified Streamly.Prelude as S
878-- import Network.HTTP.Simple
879--
880-- main = S.'drain' . 'parallely' $ google \<> bing \<> duckduckgo
881-- where
882-- google = get "https://www.google.com/search?q=haskell"
883-- bing = get "https://www.bing.com/search?q=haskell"
884-- duckduckgo = get "https://www.duckduckgo.com/?q=haskell"
885-- get s = S.'yieldM' (httpNoBody (parseRequest_ s) >> putStrLn (show s))
886-- @
887--
888-- The polymorphic version of the binary operation '<>' of the 'Parallel' type
889-- is 'parallel'. We can use 'parallel' to join streams in a fairly concurrent
890-- manner irrespective of the type, notice that we have not used the
891-- 'parallely' combinator in the following example:
892--
893-- @
894-- main = S.'drain' $ delay 3 \`parallel` delay 2 \`wAsync` delay 1
895-- @
896-- @
897-- ThreadId 42: Delay 1
898-- ThreadId 41: Delay 2
899-- ThreadId 40: Delay 3
900-- @
901--
902-- Note that this style of composition cannot be used to combine infinite
903-- number of streams, as it will lead to an infinite sized scheduling queue.
904--
906-- XXX to be removed
907-- $custom
908--
909-- The 'mkAsync' API can be used to create references to asynchronously running
910-- stream computations. We can then use 'uncons' to explore the streams
911-- arbitrarily and then recompose individual elements to create a new stream.
912-- This way we can dynamically decide which stream to explore at any given
913-- time. Take an example of a merge sort of two sorted streams. We need to
914-- keep consuming items from the stream which has the lowest item in the sort
915-- order. This can be achieved using async references to streams. See
916-- "MergeSort.hs" in the examples directory.
918-- $monoid
919--
920-- We can use 'Monoid' instances to fold a container of streams in the desired
921-- style using 'fold' or 'foldMap'. We have also provided some fold utilities
922-- to fold streams using the polymorphic combine operations:
923--
924-- * 'foldWith' is like 'fold', it folds a 'Foldable' container of streams
925-- using the given composition operator.
926-- * 'foldMapWith' is like 'foldMap', it folds like @foldWith@ but also maps a
927-- function before folding.
928-- * 'forEachWith' is like @foldMapwith@ but the container argument comes before
929-- the function argument.
930--
931-- All of the following are equivalent and start ten concurrent tasks each with
932-- a delay from 1 to 10 seconds, resulting in the printing of each number every
933-- second:
934--
935-- @
936-- import "Streamly"
937-- import qualified "Streamly.Prelude" as S
938-- import Control.Concurrent
939--
940-- main = do
941-- S.'drain' $ 'asyncly' $ foldMap delay [1..10]
942-- S.'drain' $ S.'foldWith' 'async' (map delay [1..10])
943-- S.'drain' $ S.'foldMapWith' 'async' delay [1..10]
944-- S.'drain' $ S.'forEachWith' 'async' [1..10] delay
945-- where delay n = S.'yieldM' $ threadDelay (n * 1000000) >> print n
946-- @
948-- $nesting
949--
950-- Till now we discussed ways to apply transformations on a stream or to merge
951-- streams together to create another stream. We mentioned earlier that
952-- transforming a stream is similar to a @for@ loop in the imperative paradigm.
953-- We will now discuss the concept of a nested composition of streams which is
954-- analogous to nested @for@ loops in the imperative paradigm. Functional
955-- programmers call this style of composition a list transformer or @ListT@.
956-- Logic programmers call it a logic monad or non-deterministic composition,
957-- but for ordinary imperative minded people like me it is easier to think in
958-- terms of good old nested @for@ loops.
959--
960-- $monad
961--
962-- In functional programmer's parlance the 'Monad' instances of different
963-- 'IsStream' types implement non-determinism, exploring all possible
964-- combination of choices from both the streams. From an imperative
965-- programmer's point of view it behaves like nested loops i.e. for each
966-- element in the first stream and for each element in the second stream
967-- execute the body of the loop.
968--
969-- The 'Monad' instances of 'Serial', 'WSerial', 'Async' and 'WAsync'
970-- stream types support different flavors of nested looping. In other words,
971-- they are all variants of list transformer. The nesting behavior of these
972-- types correspond exactly to the way they merge streams as we discussed in
973-- the previous section.
974--
976-- $regularSerial
977--
978-- The 'Monad' composition of the 'Serial' type behaves like a standard list
979-- transformer. This is the default when we do not use an explicit type
980-- combinator. However, the 'serially' type combinator can be used to switch to
981-- this style of composition. We will see how this style of composition works
982-- in the following examples.
983--
984-- Let's start with an example with a simple @for@ loop without any nesting.
985-- For simplicity of illustration we are using streams of pure values in all
986-- the examples. However, the streams could also be made of monadic actions
987-- instead.
988--
989-- @
990-- import "Streamly"
991-- import qualified "Streamly.Prelude" as S
992--
993-- main = S.'drain' $ do
994-- x <- S.'fromFoldable' [3,2,1]
995-- delay x
996-- @
997-- @
998-- ThreadId 30: Delay 3
999-- ThreadId 30: Delay 2
1000-- ThreadId 30: Delay 1
1001-- @
1003-- As we can see, the code after the @fromFoldable@ statement is run three
1004-- times, once for each value of @x@ drawn from the stream. All the three
1005-- iterations are serial and run in the same thread one after another. In
1006-- imperative terms this is equivalent to a @for@ loop with three iterations.
1008-- A console echo loop copying standard input to standard output can simply be
1009-- written like this:
1011-- @
1012-- import "Streamly"
1013-- import qualified "Streamly.Prelude" as S
1015-- import Control.Monad (forever)
1017-- main = S.'drain' $ forever $ S.yieldM getLine >>= S.yieldM . putStrLn
1018-- @
1020-- When multiple streams are composed using this style they nest in a DFS
1021-- manner i.e. nested iterations of a loop are executed before we proceed to
1022-- the next iteration of the parent loop. This behaves just like nested @for@
1023-- loops in imperative programming.
1025-- @
1026-- import "Streamly"
1027-- import qualified "Streamly.Prelude" as S
1029-- main = S.'drain' $ do
1030-- x <- S.'fromFoldable' [1,2]
1031-- y <- S.'fromFoldable' [3,4]
1032-- S.'yieldM' $ putStrLn $ show (x, y)
1033-- @
1034-- @
1035-- (1,3)
1036-- (1,4)
1037-- (2,3)
1038-- (2,4)
1039-- @
1041-- Notice that this is analogous to merging streams of type 'Serial' or merging
1042-- streams using 'serial'.
1044-- $aheadNesting
1046-- The 'Monad' composition of 'Ahead' type behaves just like 'Serial' except
1047-- that it can speculatively perform a bounded number of next iterations of a
1048-- loop concurrently.
1050-- The 'aheadly' type combinator can be used to switch to this style of
1051-- composition. Alternatively, a type annotation can be used to specify the
1052-- type of the stream as 'Ahead'.
1054-- @
1055-- import "Streamly"
1056-- import qualified "Streamly.Prelude" as S
1058-- comp = S.'toList' . 'aheadly' $ do
1059-- x <- S.'fromFoldable' [3,2,1]
1060-- delay x >> return x
1062-- main = comp >>= print
1063-- @
1064-- @
1065-- ThreadId 40: Delay 1
1066-- ThreadId 39: Delay 2
1067-- ThreadId 38: Delay 3
1068-- [3,2,1]
1069-- @
1071-- This code finishes in 3 seconds, 'Serial' would take 6 seconds. As we can
1072-- see all the three iterations are concurrent and run in different threads,
1073-- however, the results are returned in the serial order.
1075-- Concurrency is demand driven, when multiple streams are composed using this
1076-- style, the iterations are executed in a depth first manner just like
1077-- 'Serial' i.e. nested iterations are executed before we proceed to the next
1078-- outer iteration. The only difference is that we may execute multiple future
1079-- iterations concurrently and keep the results ready.
1082-- $concurrentNesting
1084-- The 'Monad' composition of 'Async' type can perform the iterations of a
1085-- loop concurrently. Concurrency is demand driven i.e. more concurrent
1086-- iterations are started only if the previous iterations are not able to
1087-- produce enough output for the consumer of the output stream. This works
1088-- exactly the same way as the merging of two streams 'asyncly' works.
1089-- This is the concurrent analogue of 'Serial' style monadic composition.
1091-- The 'asyncly' type combinator can be used to switch to this style of
1092-- composition. Alternatively, a type annotation can be used to specify the
1093-- type of the stream as 'Async'.
1095-- @
1096-- import "Streamly"
1097-- import qualified "Streamly.Prelude" as S
1099-- main = S.'drain' . 'asyncly' $ do
1100-- x <- S.'fromFoldable' [3,2,1]
1101-- delay x
1102-- @
1103-- @
1104-- ThreadId 40: Delay 1
1105-- ThreadId 39: Delay 2
1106-- ThreadId 38: Delay 3
1107-- @
1109-- As we can see the code after the @fromFoldable@ statement is run three
1110-- times, once for each value of @x@. All the three iterations are concurrent
1111-- and run in different threads. The iteration with least delay finishes first.
1112-- When compared to imperative programming, this can be viewed as a @for@ loop
1113-- with three concurrent iterations.
1115-- Concurrency is demand driven just as in the case of 'async' merging.
1116-- When multiple streams are composed using this style, the iterations are
1117-- triggered in a depth first manner just like 'Serial' i.e. nested iterations are
1118-- executed before we proceed to the next iteration at higher level. However,
1119-- unlike 'Serial' more than one iterations may be started concurrently based
1120-- on the demand from the consumer of the stream.
1122-- @
1123-- import "Streamly"
1124-- import qualified "Streamly.Prelude" as S
1126-- main = S.'drain' . 'asyncly' $ do
1127-- x <- S.'fromFoldable' [1,2]
1128-- y <- S.'fromFoldable' [3,4]
1129-- S.'yieldM' $ putStrLn $ show (x, y)
1130-- @
1131-- @
1132-- (1,3)
1133-- (1,4)
1134-- (2,3)
1135-- (2,4)
1136-- @
1138-- $interleavedNesting
1140-- The 'Monad' composition of 'WSerial' type interleaves the iterations of
1141-- outer and inner loops in a nested loop composition. This works exactly the
1142-- same way as the merging of two streams in 'wSerially' fashion works. The
1143-- 'wSerially' type combinator can be used to switch to this style of
1144-- composition. Alternatively, a type annotation can be used to specify the
1145-- type of the stream as 'WSerial'.
1147-- @
1148-- import "Streamly"
1149-- import qualified "Streamly.Prelude" as S
1151-- main = S.'drain' . 'wSerially' $ do
1152-- x <- S.'fromFoldable' [1,2]
1153-- y <- S.'fromFoldable' [3,4]
1154-- S.yieldM $ putStrLn $ show (x, y)
1155-- @
1156-- @
1157-- (1,3)
1158-- (2,3)
1159-- (1,4)
1160-- (2,4)
1161-- @
1164-- $wasyncNesting
1166-- Just like 'Async' the 'Monad' composition of 'WAsync' runs the iterations of
1167-- a loop concurrently. The difference is in the nested loop behavior. The
1168-- nested loops in this type are traversed and executed in a breadth first
1169-- manner rather than the depth first manner of 'Async' style.
1170-- The loop nesting works exactly the same way as the merging of streams
1171-- 'wAsyncly' works. The 'wAsyncly' type combinator can be used to switch to
1172-- this style of composition. Alternatively, a type annotation can be used to
1173-- specify the type of the stream as 'WAsync'.
1175-- @
1176-- import "Streamly"
1177-- import qualified "Streamly.Prelude" as S
1179-- main = S.'drain' . 'wAsyncly' $ do
1180-- x <- S.'fromFoldable' [1,2]
1181-- y <- S.'fromFoldable' [3,4]
1182-- S.'yieldM' $ putStrLn $ show (x, y)
1183-- @
1184-- @
1185-- (1,3)
1186-- (2,3)
1187-- (1,4)
1188-- (2,4)
1189-- @
1191-- $parallelNesting
1193-- Just like 'Async' or 'WAsync' the 'Monad' composition of 'Parallel' runs the
1194-- iterations of a loop concurrently. The difference is in the nested loop
1195-- behavior. The streams at each nest level is run fully concurrently
1196-- irrespective of the demand. The loop nesting works exactly the same way as
1197-- the merging of streams 'parallely' works. The 'parallely' type combinator
1198-- can be used to switch to this style of composition. Alternatively, a type
1199-- annotation can be used to specify the type of the stream as 'Parallel'.
1201-- @
1202-- import "Streamly"
1203-- import qualified "Streamly.Prelude" as S
1205-- main = S.'drain' . 'parallely' $ do
1206-- x <- S.'fromFoldable' [3,2,1]
1207-- delay x
1208-- @
1209-- @
1210-- ThreadId 40: Delay 1
1211-- ThreadId 39: Delay 2
1212-- ThreadId 38: Delay 3
1213-- @
1215-- $monadExercise
1217-- Streamly code is usually written in a way that is agnostic of the
1218-- specific monadic composition type. We use a polymorphic type with a
1219-- 'IsStream' type class constraint. When running the stream we can choose the
1220-- specific mode of composition. For example take a look at the following code.
1222-- @
1223-- import "Streamly"
1224-- import qualified "Streamly.Prelude" as S
1226-- composed :: (IsStream t, Monad (t IO)) => t IO ()
1227-- composed = do
1228-- sz <- sizes
1229-- cl <- colors
1230-- sh <- shapes
1231-- S.'yieldM' $ putStrLn $ show (sz, cl, sh)
1233-- where
1235-- sizes = S.'fromFoldable' [1, 2, 3]
1236-- colors = S.'fromFoldable' ["red", "green", "blue"]
1237-- shapes = S.'fromFoldable' ["triangle", "square", "circle"]
1238-- @
1240-- Now we can interpret this in whatever way we want:
1242-- @
1243-- main = S.'drain' . 'serially' $ composed
1244-- main = S.'drain' . 'wSerially' $ composed
1245-- main = S.'drain' . 'asyncly' $ composed
1246-- main = S.'drain' . 'wAsyncly' $ composed
1247-- main = S.'drain' . 'parallely' $ composed
1248-- @
1250-- As an exercise try to figure out the output of this code for each mode of
1251-- composition.
1253-- $functor
1255-- 'fmap' transforms a stream by mapping a function on all elements of the
1256-- stream. 'fmap' behaves in the same way for all stream types, it is always
1257-- serial.
1259-- @
1260-- import "Streamly"
1261-- import qualified "Streamly.Prelude" as S
1263-- main = (S.'toList' $ fmap show $ S.'fromFoldable' [1..10]) >>= print
1264-- @
1266-- Also see the 'mapM' and 'sequence' functions for mapping actions, in the
1267-- "Streamly.Prelude" module.
1269-- $applicative
1271-- Applicative is precisely the same as the 'ap' operation of 'Monad'. For
1272-- zipping applicatives separate types 'ZipSerial' and 'ZipAsync' are
1273-- provided.
1275-- The following example uses the 'Serial' applicative, it runs all iterations
1276-- serially and takes a total 17 seconds (1 + 3 + 4 + 2 + 3 + 4):
1278-- @
1279-- import "Streamly"
1280-- import qualified "Streamly.Prelude" as S
1281-- import Control.Concurrent
1283-- s1 = d 1 <> d 2
1284-- s2 = d 3 <> d 4
1285-- d n = delay n >> return n
1287-- main = (S.'toList' . 'serially' $ (,) \<$> s1 \<*> s2) >>= print
1288-- @
1289-- @
1290-- ThreadId 36: Delay 1
1291-- ThreadId 36: Delay 3
1292-- ThreadId 36: Delay 4
1293-- ThreadId 36: Delay 2
1294-- ThreadId 36: Delay 3
1295-- ThreadId 36: Delay 4
1296-- [(1,3),(1,4),(2,3),(2,4)]
1297-- @
1299-- Similarly 'WSerial' applicative runs the iterations in an interleaved
1300-- order but since it is serial it takes a total of 17 seconds:
1302-- @
1303-- main = (S.'toList' . 'wSerially' $ (,) \<$> s1 \<*> s2) >>= print
1304-- @
1305-- @
1306-- ThreadId 36: Delay 1
1307-- ThreadId 36: Delay 3
1308-- ThreadId 36: Delay 2
1309-- ThreadId 36: Delay 3
1310-- ThreadId 36: Delay 4
1311-- ThreadId 36: Delay 4
1312-- [(1,3),(2,3),(1,4),(2,4)]
1313-- @
1315-- 'Async' can run the iterations concurrently and therefore takes a total
1316-- of 6 seconds which is max (1, 2) + max (3, 4):
1318-- @
1319-- main = (S.'toList' . 'asyncly' $ (,) \<$> s1 \<*> s2) >>= print
1320-- @
1321-- @
1322-- ThreadId 34: Delay 1
1323-- ThreadId 36: Delay 2
1324-- ThreadId 35: Delay 3
1325-- ThreadId 36: Delay 3
1326-- ThreadId 35: Delay 4
1327-- ThreadId 36: Delay 4
1328-- [(1,3),(2,3),(1,4),(2,4)]
1329-- @
1331-- Similarly 'WAsync' as well can run the iterations concurrently and
1332-- therefore takes a total of 6 seconds (2 + 4):
1334-- @
1335-- main = (S.'toList' . 'wAsyncly' $ (,) \<$> s1 \<*> s2) >>= print
1336-- @
1337-- @
1338-- ThreadId 34: Delay 1
1339-- ThreadId 36: Delay 2
1340-- ThreadId 35: Delay 3
1341-- ThreadId 36: Delay 3
1342-- ThreadId 35: Delay 4
1343-- ThreadId 36: Delay 4
1344-- [(1,3),(2,3),(1,4),(2,4)]
1345-- @
1347-- $zipping
1349-- Zipping is a special transformation where the corresponding elements of two
1350-- streams are combined together using a zip function producing a new stream of
1351-- outputs. Two different types are provided for serial and concurrent zipping.
1352-- These types provide an applicative instance that can be used to lift
1353-- functions to zip the argument streams.
1354-- Also see the zipping functions in the "Streamly.Prelude" module.
1356-- $serialzip
1358-- The applicative instance of 'ZipSerial' type zips streams serially.
1359-- 'zipSerially' type combinator can be used to switch to serial applicative
1360-- zip composition:
1362-- @
1363-- import "Streamly"
1364-- import qualified "Streamly.Prelude" as S
1365-- import Control.Concurrent
1367-- d n = delay n >> return n
1368-- s1 = 'serially' $ d 1 <> d 2
1369-- s2 = 'serially' $ d 3 <> d 4
1371-- main = (S.'toList' . 'zipSerially' $ (,) \<$> s1 \<*> s2) >>= print
1372-- @
1374-- This takes total 10 seconds to zip, which is (1 + 2 + 3 + 4) since
1375-- everything runs serially:
1377-- @
1378-- ThreadId 29: Delay 1
1379-- ThreadId 29: Delay 3
1380-- ThreadId 29: Delay 2
1381-- ThreadId 29: Delay 4
1382-- [(1,3),(2,4)]
1383-- @
1385-- $parallelzip
1387-- The applicative instance of 'ZipAsync' type zips streams concurrently.
1388-- 'zipAsyncly' type combinator can be used to switch to parallel applicative
1389-- zip composition:
1392-- @
1393-- import "Streamly"
1394-- import qualified "Streamly.Prelude" as S
1395-- import Control.Concurrent
1396-- import System.IO (stdout, hSetBuffering, BufferMode(LineBuffering))
1398-- d n = delay n >> return n
1399-- s1 = 'serially' $ d 1 <> d 2
1400-- s2 = 'serially' $ d 3 <> d 4
1402-- main = do
1403-- hSetBuffering stdout LineBuffering
1404-- (S.'toList' . 'zipAsyncly' $ (,) \<$> s1 \<*> s2) >>= print
1405-- @
1407-- This takes 7 seconds to zip, which is max (1,3) + max (2,4) because 1 and 3
1408-- are produced concurrently, and 2 and 4 are produced concurrently:
1410-- @
1411-- ThreadId 32: Delay 1
1412-- ThreadId 32: Delay 2
1413-- ThreadId 33: Delay 3
1414-- ThreadId 33: Delay 4
1415-- [(1,3),(2,4)]
1416-- @
1418-- $concurrent
1420-- When writing concurrent programs there are two distinct places where the
1421-- programmer can control the concurrency. First, when /composing/ a stream by
1422-- merging multiple streams we can choose an appropriate sum style operators to
1423-- combine them concurrently or serially. Second, when /processing/ a stream in
1424-- a monadic composition we can choose one of the monad composition types to
1425-- choose the desired type of concurrency.
1427-- In the following example the squares of @x@ and @y@ are computed
1428-- concurrently using the 'async' operation and the square roots of their
1429-- sum are computed serially because of the 'streamly' combinator. We can
1430-- choose different combinators for the monadic processing and the stream
1431-- generation, to control the concurrency. We can also use the 'asyncly'
1432-- combinator instead of explicitly folding with 'async'.
1434-- @
1435-- import "Streamly"
1436-- import qualified "Streamly.Prelude" as S
1437-- import Data.List (sum)
1439-- main = do
1440-- z \<- S.'toList'
1441-- $ 'serially' -- Serial monadic processing (sqrt below)
1442-- $ do
1443-- x2 \<- 'forEachWith' 'async' [1..100] $ -- Concurrent @"for"@ loop
1444-- \\x -> return $ x * x -- body of the loop
1445-- y2 \<- 'forEachWith' 'async' [1..100] $
1446-- \\y -> return $ y * y
1447-- return $ sqrt (x2 + y2)
1448-- print $ sum z
1449-- @
1451-- We can see how this directly maps to the imperative style
1452-- <https://en.wikipedia.org/wiki/OpenMP OpenMP> model, we use combinators
1453-- and operators instead of the ugly pragmas.
1455-- For more concurrent programming examples see,
1456-- <examples/ListDir.hs ListDir.hs>,
1457-- <examples/MergeSort.hs MergeSort.hs> and
1458-- <examples/SearchQuery.hs SearchQuery.hs> in the examples directory.
1460-- $reactive
1462-- Reactive programming is nothing but concurrent streaming which is what
1463-- streamly is all about. With streamly we can generate streams of events,
1464-- merge streams that are generated concurrently and process events
1465-- concurrently. We can do all this without any knowledge about the specifics
1466-- of the implementation of concurrency. In the following example you will see
1467-- that the code is just regular Haskell code without much streamly APIs used
1468-- (active hyperlinks are the streamly APIs) and yet it is a reactive
1469-- application.
1471-- This application has two independent and concurrent sources of event
1472-- streams, @acidRain@ and @userAction@. @acidRain@ continuously generates
1473-- events that deteriorate the health of the character in the game.
1474-- @userAction@ can be "potion" or "quit". When the user types "potion" the
1475-- health improves and the game continues.
1477-- @
1478-- {-\# LANGUAGE FlexibleContexts #-}
1480-- import "Streamly"
1481-- import "Streamly.Prelude" as S
1482-- import Control.Monad (void, when)
1483-- import Control.Monad.IO.Class (MonadIO(liftIO))
1484-- import Control.Monad.State (MonadState, get, modify, runStateT, put)
1486-- data Event = Quit | Harm Int | Heal Int deriving (Show)
1488-- userAction :: MonadAsync m => 'SerialT' m Event
1489-- userAction = S.'repeatM' $ liftIO askUser
1490-- where
1491-- askUser = do
1492-- command <- getLine
1493-- case command of
1494-- "potion" -> return (Heal 10)
1495-- "harm" -> return (Harm 10)
1496-- "quit" -> return Quit
1497-- _ -> putStrLn "Type potion or harm or quit" >> askUser
1499-- acidRain :: MonadAsync m => 'SerialT' m Event
1500-- acidRain = 'asyncly' $ 'constRate' 1 $ S.'repeatM' $ liftIO $ return $ Harm 1
1502-- data Result = Check | Done
1504-- runEvents :: (MonadAsync m, MonadState Int m) => 'SerialT' m Result
1505-- runEvents = do
1506-- event \<- userAction \`parallel` acidRain
1507-- case event of
1508-- Harm n -> modify (\\h -> h - n) >> return Check
1509-- Heal n -> modify (\\h -> h + n) >> return Check
1510-- Quit -> return Done
1512-- data Status = Alive | GameOver deriving Eq
1514-- getStatus :: (MonadAsync m, MonadState Int m) => Result -> m Status
1515-- getStatus result =
1516-- case result of
1517-- Done -> liftIO $ putStrLn "You quit!" >> return GameOver
1518-- Check -> do
1519-- h <- get
1520-- liftIO $ if (h <= 0)
1521-- then putStrLn "You die!" >> return GameOver
1522-- else putStrLn ("Health = " <> show h) >> return Alive
1524-- main :: IO ()
1525-- main = do
1526-- putStrLn "Your health is deteriorating due to acid rain,\\
1527-- \\ type \\"potion\\" or \\"quit\\""
1528-- let runGame = S.'drainWhile' (== Alive) $ S.'mapM' getStatus runEvents
1529-- void $ runStateT runGame 60
1530-- @
1532-- You can also find the source of this example in the examples directory as
1533-- <examples/AcidRain.hs AcidRain.hs>. It has been adapted from Gabriel's
1534-- <https://hackage.haskell.org/package/pipes-concurrency-2.0.8/docs/Pipes-Concurrent-Tutorial.html pipes-concurrency>
1535-- package.
1536-- This is much simpler compared to the pipes version because of the builtin
1537-- concurrency in streamly. You can also find a SDL based reactive programming
1538-- example adapted from Yampa in
1539-- <examples/CirclingSquare.hs CirclingSquare.hs>.
1541-- $performance
1543-- Streamly is highly optimized for performance, it is designed for serious
1544-- high performing, concurrent and scalable applications. We have created the
1545-- <https://hackage.haskell.org/package/streaming-benchmarks streaming-benchmarks>
1546-- package which is specifically and carefully designed to measure the
1547-- performance of Haskell streaming libraries fairly and squarely in the right
1548-- way. Streamly performs at par or even better than most streaming libraries
1549-- for serial operations even though it needs to deal with the concurrency
1550-- capability.
1552-- $interop
1554-- We can use @unfoldr@ and @uncons@ to convert one streaming type to another.
1556-- Interop with @vector@:
1558-- @
1559-- import Streamly
1560-- import qualified Streamly.Prelude as S
1561-- import qualified Data.Vector.Fusion.Stream.Monadic as V
1563-- -- | vector to streamly
1564-- fromVector :: (IsStream t, Monad m) => V.Stream m a -> t m a
1565-- fromVector = S.unfoldrM unconsV
1566-- where
1567-- unconsV v = do
1568-- r <- V.null v
1569-- if r
1570-- then return Nothing
1571-- else do
1572-- h <- V.head v
1573-- return $ Just (h, V.tail v)
1575-- -- | streamly to vector
1576-- toVector :: Monad m => SerialT m a -> V.Stream m a
1577-- toVector = V.unfoldrM (S.uncons . adapt)
1579-- main = do
1580-- S.toList (fromVector (V.fromList [1..3])) >>= print
1581-- V.toList (toVector (S.fromFoldable [1..3])) >>= print
1582-- @
1584-- Interop with @pipes@:
1586-- @
1587-- import "Streamly"
1588-- import qualified "Streamly.Prelude" as S
1589-- import qualified Pipes as P
1590-- import qualified Pipes.Prelude as P
1592-- -- | pipes to streamly
1593-- fromPipes :: (IsStream t, Monad m) => P.Producer a m r -> t m a
1594-- fromPipes = S.'unfoldrM' unconsP
1595-- where
1596-- -- Adapt P.next to return a Maybe instead of Either
1597-- unconsP p = P.next p >>= either (\\_ -> return Nothing) (return . Just)
1599-- -- | streamly to pipes
1600-- toPipes :: Monad m => SerialT m a -> P.Producer a m ()
1601-- toPipes = P.unfoldr unconsS
1602-- where
1603-- -- Adapt S.uncons to return an Either instead of Maybe
1604-- unconsS s = S.'uncons' s >>= maybe (return $ Left ()) (return . Right)
1606-- main = do
1607-- S.'toList' (fromPipes (P.each [1..3])) >>= print
1608-- P.toListM (toPipes (S.'fromFoldable' [1..3])) >>= print
1609-- @
1611-- Interop with @streaming@:
1613-- @
1614-- import "Streamly"
1615-- import qualified "Streamly.Prelude" as S
1616-- import qualified Streaming as SG
1617-- import qualified Streaming.Prelude as SG
1619-- -- | streaming to streamly
1620-- fromStreaming :: (IsStream t, MonadAsync m) => SG.Stream (SG.Of a) m r -> t m a
1621-- fromStreaming = S.unfoldrM SG.uncons
1623-- -- | streamly to streaming
1624-- toStreaming :: Monad m => SerialT m a -> SG.Stream (SG.Of a) m ()
1625-- toStreaming = SG.unfoldr unconsS
1626-- where
1627-- -- Adapt S.uncons to return an Either instead of Maybe
1628-- unconsS s = S.'uncons' s >>= maybe (return $ Left ()) (return . Right)
1630-- main = do
1631-- S.toList (fromStreaming (SG.each [1..3])) >>= print
1632-- SG.toList (toStreaming (S.fromFoldable [1..3])) >>= print
1633-- @
1635-- Interop with @conduit@:
1637-- @
1638-- import "Streamly"
1639-- import qualified "Streamly.Prelude" as S
1640-- import qualified Data.Conduit as C
1641-- import qualified Data.Conduit.List as C
1642-- import qualified Data.Conduit.Combinators as C
1644-- -- It seems there is no way out of a conduit as it does not provide an
1645-- -- uncons or a tail function. We can convert streamly to conduit though.
1647-- -- | streamly to conduit
1648-- toConduit :: Monad m => SerialT m a -> C.ConduitT i a m ()
1649-- toConduit s = C.unfoldM S.'uncons' s
1651-- main = do
1652-- C.runConduit (toConduit (S.'fromFoldable' [1..3]) C..| C.sinkList) >>= print
1653-- @
1655-- $comparison
1657-- List transformers and logic programming monads also provide a product style
1658-- composition similar to streamly, however streamly generalizes it with the
1659-- time dimension; allowing streams to be composed in an asynchronous and
1660-- concurrent fashion in many different ways. It also provides multiple
1661-- alternative ways of composing streams e.g. serial, interleaved or
1662-- concurrent.
1664-- This seemingly simple addition of asynchronicity and concurrency to product
1665-- style streaming composition unifies a number of disparate abstractions into
1666-- one powerful, concise and elegant abstraction. A wide variety of
1667-- programming problems can be solved elegantly with this abstraction. In
1668-- particular, it unifies three major programming domains namely
1669-- non-deterministic (logic) programming, concurrent programming and functional
1670-- reactive programming. In other words, you can do everything with this one
1671-- abstraction that you could do with the popular libraries listed under these
1672-- categories in the list below.
1674-- @
1675-- +-----------------+----------------+
1676-- | Non-determinism | <https://hackage.haskell.org/package/pipes pipes> |
1677-- | +----------------+
1678-- | | <https://hackage.haskell.org/package/list-t list-t> |
1679-- | +----------------+
1680-- | | <https://hackage.haskell.org/package/logict logict> |
1681-- +-----------------+----------------+
1682-- | Streaming | <https://hackage.haskell.org/package/vector vector> |
1683-- | +----------------+
1684-- | | <https://hackage.haskell.org/package/streaming streaming> |
1685-- | +----------------+
1686-- | | <https://hackage.haskell.org/package/pipes pipes> |
1687-- | +----------------+
1688-- | | <https://hackage.haskell.org/package/conduit conduit> |
1689-- +-----------------+----------------+
1690-- | Concurrency | <https://hackage.haskell.org/package/async async> |
1691-- | +----------------+
1692-- | | <https://hackage.haskell.org/package/transient transient> |
1693-- +-----------------+----------------+
1694-- | FRP | <https://hackage.haskell.org/package/Yampa Yampa> |
1695-- | +----------------+
1696-- | | <https://hackage.haskell.org/package/dunai dunai> |
1697-- | +----------------+
1698-- | | <https://hackage.haskell.org/package/reflex reflex> |
1699-- +-----------------+----------------+
1700-- @
1702-- Streamly is a list-transformer. It provides all the functionality provided
1703-- by any of the list transformer and logic programming packages listed above.
1704-- In addition, Streamly naturally integrates the concurrency dimension to the
1705-- basic list transformer functionality.
1707-- When it comes to streaming, in terms of the streaming API streamly is almost
1708-- identical to the vector package. Streamly, vector and streaming packages all
1709-- represent a stream as data and are therefore similar in the fundamental
1710-- approach to streaming. The fundamental difference is that streamly adds
1711-- concurrency support and the monad instance provides concurrent looping.
1712-- Other streaming libraries like pipes, conduit and machines represent and
1713-- compose stream processors rather than the stream data and therefore fall in
1714-- another class of streaming libraries and have comparatively more complicated
1715-- types.
1717-- When it comes to concurrency, streamly can do everything that the @async@
1718-- package can do and more. async provides applicative concurrency whereas
1719-- streamly provides both applicative and monadic concurrency. The
1720-- 'ZipAsync' type behaves like the applicative instance of async. In
1721-- comparison to transient streamly has a first class streaming interface and
1722-- is a monad transformer that can be used universally in any Haskell monad
1723-- transformer stack. Streamly was in fact originally inspired by the
1724-- concurrency implementation in @transient@ though it has no resemblance with
1725-- that and takes a lazy pull approach versus transient's strict push approach.
1727-- The non-determinism, concurrency and streaming combination make streamly a
1728-- strong reactive programming library as well. Reactive programming is
1729-- fundamentally stream of events that can be processed concurrently. The
1730-- example in this tutorial as well as the
1731-- <examples/CirclingSquare.hs CirclingSquare> example from Yampa demonstrate
1732-- the basic reactive capability of streamly. In core concepts streamly is
1733-- strikingly similar to @dunai@. dunai was designed from a FRP perspective
1734-- and streamly was originally designed from a concurrency perspective.
1735-- However, both have similarity at the core.
1737-- $furtherReading
1739-- * Read the documentation of "Streamly" module
1740-- * Read the documentation of "Streamly.Prelude" module
1741-- * See the examples in the "examples" directory of the package
1742-- * See the tests in the "test" directory of the package