1{-# OPTIONS_GHC -fno-warn-unused-imports #-}
3-- Module : Streamly.Tutorial
4-- Copyright : (c) 2017 Harendra Kumar
7-- Maintainer : harendra.kumar@gmail.com
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
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.
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.
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
37-- * The quick overview in the package <README.md README file>.
38-- * The overview of streams and folds in the "Streamly" module.
40-- Once you finish this tutorial, see the last section for further reading
43module Streamly.Tutorial
48 -- * Concurrent Streams
51 -- * Combining Streams
54 -- * Imports and Supporting Code
57 -- * Generating Streams
60 -- * Generating Streams Concurrently
61 -- $generatingConcurrently
63 -- * Eliminating Streams
66 -- * Concurrent Pipeline Stages
67 -- $concurrentApplication
69 -- * Transforming Streams
72 -- * Mapping Concurrently
73 -- $concurrentTransformation
80 -- *** Deep Serial Composition ('Serial')
83 -- *** Wide Serial Composition ('WSerial')
86 -- *** Deep Speculative Composition ('Ahead')
89 -- *** Deep Asynchronous Composition ('Async')
92 -- *** Wide Asynchronous Composition ('WAsync')
95 -- *** Parallel Asynchronous Composition ('Parallel')
98 -- XXX we should deprecate and remove the mkAsync API
111 -- *** Deep Serial Nesting ('Serial')
114 -- *** Wide Serial Nesting ('WSerial')
115 -- $interleavedNesting
117 -- *** Deep Speculative Nesting ('Ahead')
120 -- *** Deep Asynchronous Nesting ('Async')
121 -- $concurrentNesting
123 -- *** Wide Asynchronous Nesting ('WAsync')
126 -- *** Parallel Asynchronous Nesting ('Parallel')
144 -- ** Parallel Zipping
147 -- * Monad transformers
148 -- $monadtransformers
150 -- * Concurrent Programming
153 -- * Reactive Programming
156 -- * Writing Concurrent Programs
162 -- * Interoperation with Streaming Libraries
165 -- * Comparison with Existing Packages
168 -- * Where to go next?
174import Streamly.Prelude
176import Control.Applicative
178import Control.Monad.IO.Class (MonadIO(..))
179import Control.Monad.Trans.Class (MonadTrans (lift))
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
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
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".
209-- Many stream operations can be done concurrently:
211-- * Streams can be generated concurrently.
213-- * Streams can be merged concurrently.
215-- * Multiple stages in a streaming pipeline can run concurrently.
217-- * Streams can be mapped and zipped concurrently.
219-- * In monadic composition they combine like a list transformer,
220-- providing concurrent non-determinism.
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.
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.
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-- +------------+--------------+--------------+--------------+
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.
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.
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
284-- +------------+-----------+
286-- +============+===========+
287-- | 'Serial' | 'WSerial' |
288-- +------------+-----------+
289-- | 'Ahead' | 'WAhead' |
290-- +------------+-----------+
291-- | 'Async' | 'WAsync' |
292-- +------------+-----------+
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.
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
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
328-- Similarly we have monad transformer types for other stream types as well viz.
329-- 'WSerialT', 'AsyncT', 'WAsyncT' and 'ParallelT'.
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'.
335-- > 'drain' $ liftIO $ putStrLn "Hello world!"
337-- > 'drain' $ lift $ putStrLn "Hello world!"
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.
348-- > import "Streamly"
349-- > import "Streamly.Prelude" ((|:))
350-- > import qualified "Streamly.Prelude" as S
353-- 'nil' represents an empty stream and 'consM' or its operator form '|:' adds
354-- a monadic action at the head of the stream.
357-- > S.'toList' S.'nil'
359-- > S.'toList' $ 'getLine' |: 'getLine' |: S.'nil'
365-- To create a singleton stream from a pure value use 'yield' or 'pure' and to
366-- create a singleton stream from a monadic action use 'yieldM'. Note that in
367-- case of Zip applicative streams "pure" repeats the value to generate an
371-- > S.'toList' $ 'pure' 1
373-- > S.'toList' $ 'yield' 1
375-- > S.'toList' $ S.'yieldM' 'getLine'
380-- To create a stream from pure values in a 'Foldable' container use
381-- 'fromFoldable' which is equivalent to a fold using 'cons' and 'nil':
384-- > S.'toList' $ S.'fromFoldable' [1..3]
386-- > S.'toList' $ 'Prelude.foldr' S.'cons' S.'nil' [1..3]
390-- To create a stream from monadic actions in a 'Foldable' container just use a
391-- right fold using 'consM' and 'nil':
394-- > 'drain' $ 'Prelude.foldr' ('|:') S.'nil' ['putStr' "Hello ", 'putStrLn' "world!"]
398-- For more ways to construct a stream see the module "Streamly.Prelude".
400-- $generatingConcurrently
402-- Monadic construction and generation functions like 'consM', 'unfoldrM',
403-- 'replicateM', 'repeatM', 'iterateM' and 'fromFoldableM' work concurrently
404-- when used with appropriate stream type combinator. The pure versions of
405-- these APIs are not concurrent, however you can use the monadic versions even
406-- for pure computations by wrapping the pure value in a monad to get the
407-- concurrent generation capability where required.
409-- The following code finishes in 3 seconds (6 seconds when serial):
412-- > let p n = threadDelay (n * 1000000) >> return n
413-- > S.'toList' $ 'parallely' $ p 3 |: p 2 |: p 1 |: S.'nil'
415-- > S.'toList' $ 'aheadly' $ p 3 |: p 2 |: p 1 |: S.'nil'
418-- The following finishes in 10 seconds (100 seconds when serial):
421-- > 'drain' $ 'asyncly' $ S.'replicateM' 10 $ p 10
427-- We have already seen 'drain' and 'toList' to eliminate a stream in the
428-- examples above. 'drain' runs a stream discarding the results i.e. only
429-- for effects. 'toList' runs the stream and collects the results in a list.
431-- For other ways to eliminate a stream see the @Folding@ section in
432-- "Streamly.Prelude" module.
436-- Transformation over a stream is the equivalent of a @for@ loop construct in
437-- imperative paradigm. We iterate over every element in the stream and perform
438-- certain transformations for each element. Transformations may involve
439-- mapping functions over the elements, filtering elements from the stream or
440-- folding all the elements in the stream into a single value. Streamly streams
441-- are exactly like lists and you can perform all the transformations in the
442-- same way as you would on lists.
444-- Here is a simple console echo program that just echoes every input line,
448-- > 'drain' $ S.'repeatM' getLine & S.'mapM' putStrLn
451-- The following code snippet reads lines from standard input, filters blank
452-- lines, drops the first non-blank line, takes the next two, up cases them,
453-- numbers them and prints them:
457-- import qualified "Streamly.Prelude" as S
458-- import Data.Char (toUpper)
459-- import Data.Function ((&))
462-- S.'repeatM' getLine
463-- & S.'filter' (not . null)
466-- & fmap (map toUpper)
467-- & S.'zipWith' (\\n s -> show n ++ " " ++ s) (S.'fromFoldable' [1..])
468-- & S.'mapM' putStrLn
471-- $concurrentTransformation
473-- Monadic transformation functions 'mapM' and 'sequence' work concurrently
474-- when used with appropriate stream type combinators. The pure versions do not
475-- work concurrently, however you can use the monadic versions even for pure
476-- computations to get the concurrent transformation capability where required.
478-- This would print a value every second (2 seconds when serial):
481-- > let p n = threadDelay (n * 1000000) >> return n
482-- > drain $ aheadly $ S.'mapM' (\\x -> p 1 >> print x) (serially $ repeatM (p 1))
486-- $concurrentApplication
488-- The concurrent function application operators '|$' and '|&' apply a stream
489-- argument to a stream function concurrently to compose a concurrent pipeline
490-- of stream processing functions:
492-- Because both the stages run concurrently, we would see a delay of only 1
493-- second instead of 2 seconds in the following:
496-- > let p n = threadDelay (n * 1000000) >> return n
497-- > drain $ S.'repeatM' (p 1) '|&' S.'mapM' (\\x -> p 1 >> print x)
502-- We can combine two streams into a single stream using semigroup composition
503-- operation '<>'. Streams can be combined in many different ways as described
504-- in the following sections, the '<>' operation behaves differently depending
505-- on the stream type in effect. The stream type and therefore the composition
506-- style can be changed at any point using one of the type combinators as
511-- In most of example snippets we do not repeat the imports. Where imports are
512-- not explicitly specified use the imports shown below.
516-- import "Streamly.Prelude" ((|:), nil)
517-- import qualified "Streamly.Prelude" as S
519-- import Control.Concurrent
520-- import Control.Monad (forever)
523-- To illustrate concurrent vs serial composition aspects, we will use the
524-- following @delay@ function to introduce a sleep or delay specified in
525-- seconds. After the delay it prints the number of seconds it slept.
528-- delay n = S.'yieldM' $ do
529-- threadDelay (n * 1000000)
531-- putStrLn (show tid ++ ": Delay " ++ show n)
536-- The 'Semigroup' operation '<>' of the 'Serial' type combines the two streams
537-- in a /serial depth first/ manner. We use the 'serially' type combinator to
538-- effect 'Serial' style of composition. We can also use an explicit 'Serial'
539-- type annotation for the stream to achieve the same effect. However, since
540-- 'Serial' is the default type unless explicitly specified by using a
541-- combinator, we can omit using an explicit combinator or type annotation for
542-- this style of composition.
544-- When two streams with multiple elements are combined in this manner, the
545-- monadic actions in the two streams are performed sequentially i.e. first all
546-- actions in the first stream are performed sequentially and then all actions
547-- in the second stream are performed sequentially. We call it
548-- /serial depth first/ as the full depth of one stream is fully traversed
549-- before we move to the next. The following example prints the sequence 1, 2,
553-- main = 'drain' $ (print 1 |: print 2 |: nil) <> (print 3 |: print 4 |: nil)
562-- All actions in both the streams are performed serially in the same thread.
563-- In the following example we can see that all actions are performed in the
564-- same thread and take a combined total of @3 + 2 + 1 = 6@ seconds:
567-- main = 'drain' $ delay 3 <> delay 2 <> delay 1
570-- ThreadId 36: Delay 3
571-- ThreadId 36: Delay 2
572-- ThreadId 36: Delay 1
575-- The polymorphic version of the binary operation '<>' of the 'Serial' type is
576-- 'serial'. We can use 'serial' to join streams in a sequential manner
577-- irrespective of the type of stream:
580-- main = 'drain' $ (print 1 |: print 2 |: nil) \`serial` (print 3 |: print 4 |: nil)
585-- The 'Semigroup' operation '<>' of the 'WSerial' type combines the two
586-- streams in a /serial breadth first/ manner. We use the 'wSerially' type
587-- combinator to effect 'WSerial' style of composition. We can also use the
588-- 'WSerial' type annotation for the stream to achieve the same effect.
590-- When two streams with multiple elements are combined in this manner, we
591-- traverse all the streams in a breadth first manner i.e. one action from each
592-- stream is performed and yielded to the resulting stream before we come back
593-- to the first stream again and so on.
594-- The following example prints the sequence 1, 3, 2, 4
597-- main = 'drain' . 'wSerially' $ (print 1 |: print 2 |: nil) <> (print 3 |: print 4 |: nil)
606-- Even though the monadic actions of the two streams are performed in an
607-- interleaved manner they are all performed serially in the same thread. In
608-- the following example we can see that all actions are performed in the same
609-- thread and take a combined total of @3 + 2 + 1 = 6@ seconds:
612-- main = 'drain' . 'wSerially' $ delay 3 <> delay 2 <> delay 1
615-- ThreadId 36: Delay 3
616-- ThreadId 36: Delay 2
617-- ThreadId 36: Delay 1
620-- The polymorphic version of the 'WSerial' binary operation '<>' is called
621-- 'wSerial'. We can use 'wSerial' to join streams in an interleaved manner
622-- irrespective of the type, notice that we have not used the 'wSerially'
623-- combinator in the following example:
626-- main = 'drain' $ (print 1 |: print 2 |: nil) \`wSerial` (print 3 |: print 4 |: nil)
635-- Note that this composition cannot be used to fold infinite number of streams
636-- since it requires preserving the state until a stream is finished.
640-- The 'Semigroup' operation '<>' of the 'Ahead' type combines two streams in a
641-- /serial depth first/ manner with concurrent lookahead. We use the 'aheadly'
642-- type combinator to effect 'Ahead' style of composition. We can also use an
643-- explicit 'Ahead' type annotation for the stream to achieve the same effect.
645-- When two streams are combined in this manner, the streams are traversed in
646-- depth first manner just like 'Serial', however it can execute the next
647-- stream concurrently and keep the results ready when its turn arrives.
648-- Concurrent execution of the next stream(s) is performed if the first stream
649-- blocks or if it cannot produce output at the rate that is enough to meet the
650-- consumer demand. Multiple streams can be executed concurrently to meet the
651-- demand. The following example would print the result in a second even
652-- though each action in each stream takes one second:
656-- xs \<- 'toList' . 'aheadly' $ (p 1 |: p 2 |: nil) <> (p 3 |: p 4 |: nil)
658-- where p n = threadDelay 1000000 >> return n
664-- Each stream is constructed 'aheadly' and then both the streams are merged
665-- 'aheadly', therefore, all the actions can run concurrently but the result is
666-- presented in serial order.
668-- You can also use the polymorphic combinator 'ahead' in place of '<>' to
669-- compose any type of streams in this manner.
673-- The 'Semigroup' operation '<>' of the 'Async' type combines the two
674-- streams in a depth first manner with parallel look ahead. We use the
675-- 'asyncly' type combinator to effect 'Async' style of composition. We
676-- can also use the 'Async' type annotation for the stream type to achieve
679-- When two streams with multiple elements are combined in this manner, the
680-- streams are traversed in depth first manner just like 'Serial', however it
681-- can execute the next stream concurrently and return the results from it
682-- as they arrive i.e. the results from the next stream may be yielded even
683-- before the results from the first stream. Concurrent execution of the next
684-- stream(s) is performed if the first stream blocks or if it cannot produce
685-- output at the rate that is enough to meet the consumer demand. Multiple
686-- streams can be executed concurrently to meet the demand.
687-- In the example below each element in the stream introduces a constant delay
688-- of 1 second, however, it takes just one second to produce all the results.
689-- The results are not guaranteed to be in any particular order:
693-- xs \<- 'drain' . 'asyncly' $ (p 1 |: p 2 |: nil) <> (p 3 |: p 4 |: nil)
695-- where p n = threadDelay 1000000 >> return n
701-- The constituent streams are also composed in 'Async' manner and the
702-- composition of streams too. We can compose the constituent streams to run
703-- serially, in that case it would take 2 seconds to produce all the results.
704-- The elements in the serial streams would be in serial order in the results:
708-- xs \<- 'drain' . 'asyncly' $ (serially $ p 1 |: p 2 |: nil) <> (serially $ p 3 |: p 4 |: nil)
710-- where p n = threadDelay 1000000 >> return n
716-- In the following example we can see that new threads are started when a
717-- computation blocks. Notice that the output from the stream with the
718-- shortest delay is printed first. The whole computation takes @maximum of
719-- (3, 2, 1) = 3@ seconds:
722-- main = 'drain' . 'asyncly' $ delay 3 '<>' delay 2 '<>' delay 1
725-- ThreadId 42: Delay 1
726-- ThreadId 41: Delay 2
727-- ThreadId 40: Delay 3
730-- When we have a tree of computations composed using this style, the tree is
731-- traversed in DFS style just like the 'Serial' style, the only difference is
732-- that here we can move on to executing the next stream if a stream blocks.
733-- However, we will not start new threads if we have sufficient output to
734-- saturate the consumer. This is why we call it left-biased demand driven or
735-- adaptive concurrency style, the concurrency tends to stay on the left side
736-- of the composition as long as possible. More threads are started based on
737-- the pull rate of the consumer. The following example prints an output every
738-- second as all of the actions are concurrent.
741-- main = 'drain' . 'asyncly' $ (delay 1 <> delay 2) <> (delay 3 <> delay 4)
750-- All the computations may even run in a single thread when more threads are
751-- not needed. As you can see, in the following example the computations are
752-- run in a single thread one after another, because none of them blocks.
753-- However, if the thread consuming the stream were faster than the producer
754-- then it would have started parallel threads for each computation to keep up
755-- even if none of them blocks:
758-- main = 'drain' . 'asyncly' $ traced (sqrt 9) '<>' traced (sqrt 16) '<>' traced (sqrt 25)
759-- where traced m = S.'yieldM' (myThreadId >>= print) >> return m
767-- Note that the order of printing in the above examples may change due to
768-- variations in scheduling latencies for concurrent threads.
770-- The polymorphic version of the 'Async' binary operation '<>' is called
771-- 'async'. We can use 'async' to join streams in a left biased
772-- adaptively concurrent manner irrespective of the type, notice that we have
773-- not used the 'asyncly' combinator in the following example:
776-- main = 'drain' $ delay 3 \`async` delay 2 \`async` delay 1
779-- ThreadId 42: Delay 1
780-- ThreadId 41: Delay 2
781-- ThreadId 40: Delay 3
784-- Since the concurrency provided by this operator is demand driven it cannot
785-- be used when the composed computations start timers that are relative to
786-- each other because all computations may not be started at the same time and
787-- therefore timers in all of them may not start at the same time. When
788-- relative timing among all computations is important or when we need to start
789-- all computations at once for any reason 'Parallel' style must be used
792-- 'Async' style should be preferred over 'Parallel' or 'WAsync' unless you
793-- really need those. It utilizes the resources optimally. It should be used
794-- when we know that the computations can run in parallel but we do not care if
795-- they actually run in parallel or not, that decision can be left to the
796-- scheduler based on demand. Also, note that this operator can be used to fold
797-- infinite number of streams in contrast to the 'Parallel' or 'WAsync' styles,
798-- because it does not require us to run all of them at the same time in a fair
803-- The 'Semigroup' operation '<>' of the 'WAsync' type combines two streams in
804-- a concurrent manner using /breadth first traversal/. We use the 'wAsyncly'
805-- type combinator to effect 'WAsync' style of composition. We can also use the
806-- 'WAsync' type annotation for the stream to achieve the same effect.
808-- When streams with multiple elements are combined in this manner, we traverse
809-- all the streams concurrently in a breadth first manner i.e. one action from
810-- each stream is performed and yielded to the resulting stream before we come
811-- back to the first stream again and so on. Even though we execute the actions
812-- in a breadth first order the outputs are consumed on a first come first
815-- In the following example we can see that outputs are produced in the breadth
816-- first traversal order but this is not guaranteed.
819-- main = 'drain' . 'wAsyncly' $ (serially $ print 1 |: print 2 |: nil) <> (serially $ print 3 |: print 4 |: nil)
828-- The polymorphic version of the binary operation '<>' of the 'WAsync' type is
829-- 'wAsync'. We can use 'wAsync' to join streams using a breadth first
830-- concurrent traversal irrespective of the type, notice that we have not used
831-- the 'wAsyncly' combinator in the following example:
834-- main = 'drain' $ delay 3 \`wAsync` delay 2 \`wAsync` delay 1
837-- ThreadId 42: Delay 1
838-- ThreadId 41: Delay 2
839-- ThreadId 40: Delay 3
842-- Since the concurrency provided by this style is demand driven it may not
843-- be used when the composed computations start timers that are relative to
844-- each other because all computations may not be started at the same time and
845-- therefore timers in all of them may not start at the same time. When
846-- relative timing among all computations is important or when we need to start
847-- all computations at once for any reason 'Parallel' style must be used
853-- The 'Semigroup' operation '<>' of the 'Parallel' type combines the two
854-- streams in a fairly concurrent manner with round robin scheduling. We use
855-- the 'parallely' type combinator to effect 'Parallel' style of composition.
856-- We can also use the 'Parallel' type annotation for the stream type to
857-- achieve the same effect.
859-- When two streams with multiple elements are combined in this manner, the
860-- monadic actions in both the streams are performed concurrently with a fair
861-- round robin scheduling. The outputs are yielded in the order in which the
862-- actions complete. This is pretty similar to the 'WAsync' type, the
863-- difference is that 'WAsync' is adaptive to the consumer demand and may or
864-- may not execute all actions in parallel depending on the demand, whereas
865-- 'Parallel' runs all the streams in parallel irrespective of the demand.
867-- The following example sends a query to all the three search engines in
868-- parallel and prints the name of the search engines in the order in which the
873-- import qualified Streamly.Prelude as S
874-- import Network.HTTP.Simple
876-- main = 'drain' . 'parallely' $ google \<> bing \<> duckduckgo
878-- google = get "https://www.google.com/search?q=haskell"
879-- bing = get "https://www.bing.com/search?q=haskell"
880-- duckduckgo = get "https://www.duckduckgo.com/?q=haskell"
881-- get s = S.'yieldM' (httpNoBody (parseRequest_ s) >> putStrLn (show s))
884-- The polymorphic version of the binary operation '<>' of the 'Parallel' type
885-- is 'parallel'. We can use 'parallel' to join streams in a fairly concurrent
886-- manner irrespective of the type, notice that we have not used the
887-- 'parallely' combinator in the following example:
890-- main = 'drain' $ delay 3 \`parallel` delay 2 \`wAsync` delay 1
893-- ThreadId 42: Delay 1
894-- ThreadId 41: Delay 2
895-- ThreadId 40: Delay 3
898-- Note that this style of composition cannot be used to combine infinite
899-- number of streams, as it will lead to an infinite sized scheduling queue.
905-- The 'mkAsync' API can be used to create references to asynchronously running
906-- stream computations. We can then use 'uncons' to explore the streams
907-- arbitrarily and then recompose individual elements to create a new stream.
908-- This way we can dynamically decide which stream to explore at any given
909-- time. Take an example of a merge sort of two sorted streams. We need to
910-- keep consuming items from the stream which has the lowest item in the sort
911-- order. This can be achieved using async references to streams. See
912-- "MergeSort.hs" in the examples directory.
916-- We can use 'Monoid' instances to fold a container of streams in the desired
917-- style using 'fold' or 'foldMap'. We have also provided some fold utilities
918-- to fold streams using the polymorphic combine operations:
920-- * 'foldWith' is like 'fold', it folds a 'Foldable' container of streams
921-- using the given composition operator.
922-- * 'foldMapWith' is like 'foldMap', it folds like @foldWith@ but also maps a
923-- function before folding.
924-- * 'forEachWith' is like @foldMapwith@ but the container argument comes before
925-- the function argument.
927-- All of the following are equivalent and start ten concurrent tasks each with
928-- a delay from 1 to 10 seconds, resulting in the printing of each number every
933-- import qualified "Streamly.Prelude" as S
934-- import Control.Concurrent
937-- 'drain' $ 'asyncly' $ foldMap delay [1..10]
938-- 'drain' $ 'foldWith' 'async' (map delay [1..10])
939-- 'drain' $ 'foldMapWith' 'async' delay [1..10]
940-- 'drain' $ 'forEachWith' 'async' [1..10] delay
941-- where delay n = S.'yieldM' $ threadDelay (n * 1000000) >> print n
946-- Till now we discussed ways to apply transformations on a stream or to merge
947-- streams together to create another stream. We mentioned earlier that
948-- transforming a stream is similar to a @for@ loop in the imperative paradigm.
949-- We will now discuss the concept of a nested composition of streams which is
950-- analogous to nested @for@ loops in the imperative paradigm. Functional
951-- programmers call this style of composition a list transformer or @ListT@.
952-- Logic programmers call it a logic monad or non-deterministic composition,
953-- but for ordinary imperative minded people like me it is easier to think in
954-- terms of good old nested @for@ loops.
958-- In functional programmer's parlance the 'Monad' instances of different
959-- 'IsStream' types implement non-determinism, exploring all possible
960-- combination of choices from both the streams. From an imperative
961-- programmer's point of view it behaves like nested loops i.e. for each
962-- element in the first stream and for each element in the second stream
963-- execute the body of the loop.
965-- The 'Monad' instances of 'Serial', 'WSerial', 'Async' and 'WAsync'
966-- stream types support different flavors of nested looping. In other words,
967-- they are all variants of list transformer. The nesting behavior of these
968-- types correspond exactly to the way they merge streams as we discussed in
969-- the previous section.
974-- The 'Monad' composition of the 'Serial' type behaves like a standard list
975-- transformer. This is the default when we do not use an explicit type
976-- combinator. However, the 'serially' type combinator can be used to switch to
977-- this style of composition. We will see how this style of composition works
978-- in the following examples.
980-- Let's start with an example with a simple @for@ loop without any nesting.
981-- For simplicity of illustration we are using streams of pure values in all
982-- the examples. However, the streams could also be made of monadic actions
987-- import qualified "Streamly.Prelude" as S
989-- main = 'drain' $ do
990-- x <- S.'fromFoldable' [3,2,1]
994-- ThreadId 30: Delay 3
995-- ThreadId 30: Delay 2
996-- ThreadId 30: Delay 1
999-- As we can see, the code after the @fromFoldable@ statement is run three
1000-- times, once for each value of @x@ drawn from the stream. All the three
1001-- iterations are serial and run in the same thread one after another. In
1002-- imperative terms this is equivalent to a @for@ loop with three iterations.
1004-- A console echo loop copying standard input to standard output can simply be
1005-- written like this:
1009-- import qualified "Streamly.Prelude" as S
1011-- main = 'drain' $ forever $ S.yieldM getLine >>= S.yieldM . putStrLn
1014-- When multiple streams are composed using this style they nest in a DFS
1015-- manner i.e. nested iterations of a loop are executed before we proceed to
1016-- the next iteration of the parent loop. This behaves just like nested @for@
1017-- loops in imperative programming.
1021-- import qualified "Streamly.Prelude" as S
1023-- main = 'drain' $ do
1024-- x <- S.'fromFoldable' [1,2]
1025-- y <- S.'fromFoldable' [3,4]
1026-- S.'yieldM' $ putStrLn $ show (x, y)
1035-- Notice that this is analogous to merging streams of type 'Serial' or merging
1036-- streams using 'serial'.
1040-- The 'Monad' composition of 'Ahead' type behaves just like 'Serial' except
1041-- that it can speculatively perform a bounded number of next iterations of a
1042-- loop concurrently.
1044-- The 'aheadly' type combinator can be used to switch to this style of
1045-- composition. Alternatively, a type annotation can be used to specify the
1046-- type of the stream as 'Ahead'.
1050-- import "Streamly.Prelude" as S
1052-- comp = 'toList' . 'aheadly' $ do
1053-- x <- S.'fromFoldable' [3,2,1]
1054-- delay x >> return x
1056-- main = comp >> print
1059-- ThreadId 40: Delay 1
1060-- ThreadId 39: Delay 2
1061-- ThreadId 38: Delay 3
1065-- This code finishes in 3 seconds, 'Serial' would take 6 seconds. As we can
1066-- see all the three iterations are concurrent and run in different threads,
1067-- however, the results are returned in the serial order.
1069-- Concurrency is demand driven, when multiple streams are composed using this
1070-- style, the iterations are executed in a depth first manner just like
1071-- 'Serial' i.e. nested iterations are executed before we proceed to the next
1072-- outer iteration. The only difference is that we may execute multiple future
1073-- iterations concurrently and keep the results ready.
1076-- $concurrentNesting
1078-- The 'Monad' composition of 'Async' type can perform the iterations of a
1079-- loop concurrently. Concurrency is demand driven i.e. more concurrent
1080-- iterations are started only if the previous iterations are not able to
1081-- produce enough output for the consumer of the output stream. This works
1082-- exactly the same way as the merging of two streams 'asyncly' works.
1083-- This is the concurrent analogue of 'Serial' style monadic composition.
1085-- The 'asyncly' type combinator can be used to switch to this style of
1086-- composition. Alternatively, a type annotation can be used to specify the
1087-- type of the stream as 'Async'.
1091-- import "Streamly.Prelude"
1093-- main = 'drain' . 'asyncly' $ do
1094-- x <- S.'fromFoldable' [3,2,1]
1098-- ThreadId 40: Delay 1
1099-- ThreadId 39: Delay 2
1100-- ThreadId 38: Delay 3
1103-- As we can see the code after the @fromFoldable@ statement is run three
1104-- times, once for each value of @x@. All the three iterations are concurrent
1105-- and run in different threads. The iteration with least delay finishes first.
1106-- When compared to imperative programming, this can be viewed as a @for@ loop
1107-- with three concurrent iterations.
1109-- Concurrency is demand driven just as in the case of 'async' merging.
1110-- When multiple streams are composed using this style, the iterations are
1111-- triggered in a depth first manner just like 'Serial' i.e. nested iterations are
1112-- executed before we proceed to the next iteration at higher level. However,
1113-- unlike 'Serial' more than one iterations may be started concurrently based
1114-- on the demand from the consumer of the stream.
1118-- import qualified "Streamly.Prelude" as S
1120-- main = 'drain' . 'asyncly' $ do
1121-- x <- S.'fromFoldable' [1,2]
1122-- y <- S.'fromFoldable' [3,4]
1123-- S.'yieldM' $ putStrLn $ show (x, y)
1132-- $interleavedNesting
1134-- The 'Monad' composition of 'WSerial' type interleaves the iterations of
1135-- outer and inner loops in a nested loop composition. This works exactly the
1136-- same way as the merging of two streams in 'wSerially' fashion works. The
1137-- 'wSerially' type combinator can be used to switch to this style of
1138-- composition. Alternatively, a type annotation can be used to specify the
1139-- type of the stream as 'WSerial'.
1143-- import qualified "Streamly.Prelude" as S
1145-- main = 'drain' . 'wSerially' $ do
1146-- x <- S.'fromFoldable' [1,2]
1147-- y <- S.'fromFoldable' [3,4]
1148-- S.yieldM $ putStrLn $ show (x, y)
1160-- Just like 'Async' the 'Monad' composition of 'WAsync' runs the iterations of
1161-- a loop concurrently. The difference is in the nested loop behavior. The
1162-- nested loops in this type are traversed and executed in a breadth first
1163-- manner rather than the depth first manner of 'Async' style.
1164-- The loop nesting works exactly the same way as the merging of streams
1165-- 'wAsyncly' works. The 'wAsyncly' type combinator can be used to switch to
1166-- this style of composition. Alternatively, a type annotation can be used to
1167-- specify the type of the stream as 'WAsync'.
1171-- import qualified "Streamly.Prelude" as S
1173-- main = 'drain' . 'wAsyncly' $ do
1174-- x <- S.'fromFoldable' [1,2]
1175-- y <- S.'fromFoldable' [3,4]
1176-- S.'yieldM' $ putStrLn $ show (x, y)
1187-- Just like 'Async' or 'WAsync' the 'Monad' composition of 'Parallel' runs the
1188-- iterations of a loop concurrently. The difference is in the nested loop
1189-- behavior. The streams at each nest level is run fully concurrently
1190-- irrespective of the demand. The loop nesting works exactly the same way as
1191-- the merging of streams 'parallely' works. The 'parallely' type combinator
1192-- can be used to switch to this style of composition. Alternatively, a type
1193-- annotation can be used to specify the type of the stream as 'Parallel'.
1197-- import qualified "Streamly.Prelude" as S
1199-- main = 'drain' . 'parallely' $ do
1200-- x <- S.'fromFoldable' [3,2,1]
1204-- ThreadId 40: Delay 1
1205-- ThreadId 39: Delay 2
1206-- ThreadId 38: Delay 3
1211-- Streamly code is usually written in a way that is agnostic of the
1212-- specific monadic composition type. We use a polymorphic type with a
1213-- 'IsStream' type class constraint. When running the stream we can choose the
1214-- specific mode of composition. For example take a look at the following code.
1218-- import qualified "Streamly.Prelude" as S
1220-- composed :: (IsStream t, Monad (t IO)) => t IO ()
1225-- S.'yieldM' $ putStrLn $ show (sz, cl, sh)
1229-- sizes = S.'fromFoldable' [1, 2, 3]
1230-- colors = S.'fromFoldable' ["red", "green", "blue"]
1231-- shapes = S.'fromFoldable' ["triangle", "square", "circle"]
1234-- Now we can interpret this in whatever way we want:
1237-- main = 'drain' . 'serially' $ composed
1238-- main = 'drain' . 'wSerially' $ composed
1239-- main = 'drain' . 'asyncly' $ composed
1240-- main = 'drain' . 'wAsyncly' $ composed
1241-- main = 'drain' . 'parallely' $ composed
1244-- As an exercise try to figure out the output of this code for each mode of
1249-- 'fmap' transforms a stream by mapping a function on all elements of the
1250-- stream. 'fmap' behaves in the same way for all stream types, it is always
1255-- import qualified "Streamly.Prelude" as S
1257-- main = (S.'toList' $ fmap show $ S.'fromFoldable' [1..10]) >>= print
1260-- Also see the 'mapM' and 'sequence' functions for mapping actions, in the
1261-- "Streamly.Prelude" module.
1265-- Applicative is precisely the same as the 'ap' operation of 'Monad'. For
1266-- zipping applicatives separate types 'ZipSerial' and 'ZipAsync' are
1269-- The following example uses the 'Serial' applicative, it runs all iterations
1270-- serially and takes a total 17 seconds (1 + 3 + 4 + 2 + 3 + 4):
1274-- import qualified "Streamly.Prelude" as S
1275-- import Control.Concurrent
1279-- d n = delay n >> return n
1281-- main = (S.'toList' . 'serially' $ (,) \<$> s1 \<*> s2) >>= print
1284-- ThreadId 36: Delay 1
1285-- ThreadId 36: Delay 3
1286-- ThreadId 36: Delay 4
1287-- ThreadId 36: Delay 2
1288-- ThreadId 36: Delay 3
1289-- ThreadId 36: Delay 4
1290-- [(1,3),(1,4),(2,3),(2,4)]
1293-- Similarly 'WSerial' applicative runs the iterations in an interleaved
1294-- order but since it is serial it takes a total of 17 seconds:
1297-- main = (S.'toList' . 'wSerially' $ (,) \<$> s1 \<*> s2) >>= print
1300-- ThreadId 36: Delay 1
1301-- ThreadId 36: Delay 3
1302-- ThreadId 36: Delay 2
1303-- ThreadId 36: Delay 3
1304-- ThreadId 36: Delay 4
1305-- ThreadId 36: Delay 4
1306-- [(1,3),(2,3),(1,4),(2,4)]
1309-- 'Async' can run the iterations concurrently and therefore takes a total
1310-- of 10 seconds (1 + 2 + 3 + 4):
1313-- main = (S.'toList' . 'asyncly' $ (,) \<$> s1 \<*> s2) >>= print
1316-- ThreadId 34: Delay 1
1317-- ThreadId 36: Delay 2
1318-- ThreadId 35: Delay 3
1319-- ThreadId 36: Delay 3
1320-- ThreadId 35: Delay 4
1321-- ThreadId 36: Delay 4
1322-- [(1,3),(2,3),(1,4),(2,4)]
1325-- Similarly 'WAsync' as well can run the iterations concurrently and
1326-- therefore takes a total of 10 seconds (1 + 2 + 3 + 4):
1329-- main = (S.'toList' . 'wAsyncly' $ (,) \<$> s1 \<*> s2) >>= print
1332-- ThreadId 34: Delay 1
1333-- ThreadId 36: Delay 2
1334-- ThreadId 35: Delay 3
1335-- ThreadId 36: Delay 3
1336-- ThreadId 35: Delay 4
1337-- ThreadId 36: Delay 4
1338-- [(1,3),(2,3),(1,4),(2,4)]
1343-- Zipping is a special transformation where the corresponding elements of two
1344-- streams are combined together using a zip function producing a new stream of
1345-- outputs. Two different types are provided for serial and concurrent zipping.
1346-- These types provide an applicative instance that can be used to lift
1347-- functions to zip the argument streams.
1348-- Also see the zipping functions in the "Streamly.Prelude" module.
1352-- The applicative instance of 'ZipSerial' type zips streams serially.
1353-- 'zipSerially' type combinator can be used to switch to serial applicative
1358-- import qualified "Streamly.Prelude" as S
1359-- import Control.Concurrent
1361-- d n = delay n >> return n
1362-- s1 = 'serially' $ d 1 <> d 2
1363-- s2 = 'serially' $ d 3 <> d 4
1365-- main = (S.'toList' . 'zipSerially' $ (,) \<$> s1 \<*> s2) >>= print
1368-- This takes total 10 seconds to zip, which is (1 + 2 + 3 + 4) since
1369-- everything runs serially:
1372-- ThreadId 29: Delay 1
1373-- ThreadId 29: Delay 3
1374-- ThreadId 29: Delay 2
1375-- ThreadId 29: Delay 4
1381-- The applicative instance of 'ZipAsync' type zips streams concurrently.
1382-- 'zipAsyncly' type combinator can be used to switch to parallel applicative
1388-- import qualified "Streamly.Prelude" as S
1389-- import Control.Concurrent
1390-- import System.IO (stdout, hSetBuffering, BufferMode(LineBuffering))
1392-- d n = delay n >> return n
1393-- s1 = 'serially' $ d 1 <> d 2
1394-- s2 = 'serially' $ d 3 <> d 4
1397-- hSetBuffering stdout LineBuffering
1398-- (S.'toList' . 'zipAsyncly' $ (,) \<$> s1 \<*> s2) >>= print
1401-- This takes 7 seconds to zip, which is max (1,3) + max (2,4) because 1 and 3
1402-- are produced concurrently, and 2 and 4 are produced concurrently:
1405-- ThreadId 32: Delay 1
1406-- ThreadId 32: Delay 2
1407-- ThreadId 33: Delay 3
1408-- ThreadId 33: Delay 4
1414-- When writing concurrent programs there are two distinct places where the
1415-- programmer can control the concurrency. First, when /composing/ a stream by
1416-- merging multiple streams we can choose an appropriate sum style operators to
1417-- combine them concurrently or serially. Second, when /processing/ a stream in
1418-- a monadic composition we can choose one of the monad composition types to
1419-- choose the desired type of concurrency.
1421-- In the following example the squares of @x@ and @y@ are computed
1422-- concurrently using the 'async' operation and the square roots of their
1423-- sum are computed serially because of the 'streamly' combinator. We can
1424-- choose different combinators for the monadic processing and the stream
1425-- generation, to control the concurrency. We can also use the 'asyncly'
1426-- combinator instead of explicitly folding with 'async'.
1430-- import qualified "Streamly.Prelude" as S
1431-- import Data.List (sum)
1435-- $ 'serially' -- Serial monadic processing (sqrt below)
1437-- x2 \<- 'forEachWith' 'async' [1..100] $ -- Concurrent @"for"@ loop
1438-- \\x -> return $ x * x -- body of the loop
1439-- y2 \<- 'forEachWith' 'async' [1..100] $
1440-- \\y -> return $ y * y
1441-- return $ sqrt (x2 + y2)
1445-- We can see how this directly maps to the imperative style
1446-- <https://en.wikipedia.org/wiki/OpenMP OpenMP> model, we use combinators
1447-- and operators instead of the ugly pragmas.
1449-- For more concurrent programming examples see,
1450-- <examples/ListDir.hs ListDir.hs>,
1451-- <examples/MergeSort.hs MergeSort.hs> and
1452-- <examples/SearchQuery.hs SearchQuery.hs> in the examples directory.
1456-- Reactive programming is nothing but concurrent streaming which is what
1457-- streamly is all about. With streamly we can generate streams of events,
1458-- merge streams that are generated concurrently and process events
1459-- concurrently. We can do all this without any knowledge about the specifics
1460-- of the implementation of concurrency. In the following example you will see
1461-- that the code is just regular Haskell code without much streamly APIs used
1462-- (active hyperlinks are the streamly APIs) and yet it is a reactive
1465-- This application has two independent and concurrent sources of event
1466-- streams, @acidRain@ and @userAction@. @acidRain@ continuously generates
1467-- events that deteriorate the health of the character in the game.
1468-- @userAction@ can be "potion" or "quit". When the user types "potion" the
1469-- health improves and the game continues.
1472-- {-\# LANGUAGE FlexibleContexts #-}
1475-- import "Streamly.Prelude" as S
1476-- import Control.Monad (void, when)
1477-- import Control.Monad.IO.Class (MonadIO(liftIO))
1478-- import Control.Monad.State (MonadState, get, modify, runStateT, put)
1480-- data Event = Quit | Harm Int | Heal Int deriving (Show)
1482-- userAction :: MonadAsync m => 'SerialT' m Event
1483-- userAction = S.'repeatM' $ liftIO askUser
1486-- command <- getLine
1488-- "potion" -> return (Heal 10)
1489-- "harm" -> return (Harm 10)
1490-- "quit" -> return Quit
1491-- _ -> putStrLn "Type potion or harm or quit" >> askUser
1493-- acidRain :: MonadAsync m => 'SerialT' m Event
1494-- acidRain = 'asyncly' $ 'constRate' 1 $ S.'repeatM' $ liftIO $ return $ Harm 1
1496-- data Result = Check | Done
1498-- runEvents :: (MonadAsync m, MonadState Int m) => 'SerialT' m Result
1500-- event \<- userAction \`parallel` acidRain
1502-- Harm n -> modify (\\h -> h - n) >> return Check
1503-- Heal n -> modify (\\h -> h + n) >> return Check
1504-- Quit -> return Done
1506-- data Status = Alive | GameOver deriving Eq
1508-- getStatus :: (MonadAsync m, MonadState Int m) => Result -> m Status
1509-- getStatus result =
1511-- Done -> liftIO $ putStrLn "You quit!" >> return GameOver
1514-- liftIO $ if (h <= 0)
1515-- then putStrLn "You die!" >> return GameOver
1516-- else putStrLn ("Health = " <> show h) >> return Alive
1520-- putStrLn "Your health is deteriorating due to acid rain,\\
1521-- \\ type \\"potion\\" or \\"quit\\""
1522-- let runGame = S.'drainWhile' (== Alive) $ S.'mapM' getStatus runEvents
1523-- void $ runStateT runGame 60
1526-- You can also find the source of this example in the examples directory as
1527-- <examples/AcidRain.hs AcidRain.hs>. It has been adapted from Gabriel's
1528-- <https://hackage.haskell.org/package/pipes-concurrency-2.0.8/docs/Pipes-Concurrent-Tutorial.html pipes-concurrency>
1530-- This is much simpler compared to the pipes version because of the builtin
1531-- concurrency in streamly. You can also find a SDL based reactive programming
1532-- example adapted from Yampa in
1533-- <examples/CirclingSquare.hs CirclingSquare.hs>.
1537-- Streamly is highly optimized for performance, it is designed for serious
1538-- high performing, concurrent and scalable applications. We have created the
1539-- <https://hackage.haskell.org/package/streaming-benchmarks streaming-benchmarks>
1540-- package which is specifically and carefully designed to measure the
1541-- performance of Haskell streaming libraries fairly and squarely in the right
1542-- way. Streamly performs at par or even better than most streaming libraries
1543-- for serial operations even though it needs to deal with the concurrency
1548-- We can use @unfoldr@ and @uncons@ to convert one streaming type to another.
1550-- Interop with @vector@:
1554-- import qualified Streamly.Prelude as S
1555-- import qualified Data.Vector.Fusion.Stream.Monadic as V
1557-- -- | vector to streamly
1558-- fromVector :: (IsStream t, Monad m) => V.Stream m a -> t m a
1559-- fromVector = S.unfoldrM unconsV
1564-- then return Nothing
1567-- return $ Just (h, V.tail v)
1569-- -- | streamly to vector
1570-- toVector :: Monad m => SerialT m a -> V.Stream m a
1571-- toVector = V.unfoldrM (S.uncons . adapt)
1574-- S.toList (fromVector (V.fromList [1..3])) >>= print
1575-- V.toList (toVector (S.fromFoldable [1..3])) >>= print
1578-- Interop with @pipes@:
1582-- import qualified "Streamly.Prelude" as S
1583-- import qualified Pipes as P
1584-- import qualified Pipes.Prelude as P
1586-- -- | pipes to streamly
1587-- fromPipes :: (IsStream t, Monad m) => P.Producer a m r -> t m a
1588-- fromPipes = S.'unfoldrM' unconsP
1590-- -- Adapt P.next to return a Maybe instead of Either
1591-- unconsP p = P.next p >>= either (\\_ -> return Nothing) (return . Just)
1593-- -- | streamly to pipes
1594-- toPipes :: Monad m => SerialT m a -> P.Producer a m ()
1595-- toPipes = P.unfoldr unconsS
1597-- -- Adapt S.uncons to return an Either instead of Maybe
1598-- unconsS s = S.'uncons' s >>= maybe (return $ Left ()) (return . Right)
1601-- S.'toList' (fromPipes (P.each [1..3])) >>= print
1602-- P.toListM (toPipes (S.'fromFoldable' [1..3])) >>= print
1605-- Interop with @streaming@:
1609-- import qualified "Streamly.Prelude" as S
1610-- import qualified Streaming as SG
1611-- import qualified Streaming.Prelude as SG
1613-- -- | streaming to streamly
1614-- fromStreaming :: (IsStream t, MonadAsync m) => SG.Stream (SG.Of a) m r -> t m a
1615-- fromStreaming = S.unfoldrM SG.uncons
1617-- -- | streamly to streaming
1618-- toStreaming :: Monad m => SerialT m a -> SG.Stream (SG.Of a) m ()
1619-- toStreaming = SG.unfoldr unconsS
1621-- -- Adapt S.uncons to return an Either instead of Maybe
1622-- unconsS s = S.'uncons' s >>= maybe (return $ Left ()) (return . Right)
1625-- S.toList (fromStreaming (SG.each [1..3])) >>= print
1626-- SG.toList (toStreaming (S.fromFoldable [1..3])) >>= print
1629-- Interop with @conduit@:
1633-- import qualified "Streamly.Prelude" as S
1634-- import qualified Data.Conduit as C
1635-- import qualified Data.Conduit.List as C
1636-- import qualified Data.Conduit.Combinators as C
1638-- -- It seems there is no way out of a conduit as it does not provide an
1639-- -- uncons or a tail function. We can convert streamly to conduit though.
1641-- -- | streamly to conduit
1642-- toConduit :: Monad m => SerialT m a -> C.ConduitT i a m ()
1643-- toConduit s = C.unfoldM S.'uncons' s
1646-- C.runConduit (toConduit (S.'fromFoldable' [1..3]) C..| C.sinkList) >>= print
1651-- List transformers and logic programming monads also provide a product style
1652-- composition similar to streamly, however streamly generalizes it with the
1653-- time dimension; allowing streams to be composed in an asynchronous and
1654-- concurrent fashion in many different ways. It also provides multiple
1655-- alternative ways of composing streams e.g. serial, interleaved or
1658-- This seemingly simple addition of asynchronicity and concurrency to product
1659-- style streaming composition unifies a number of disparate abstractions into
1660-- one powerful, concise and elegant abstraction. A wide variety of
1661-- programming problems can be solved elegantly with this abstraction. In
1662-- particular, it unifies three major programming domains namely
1663-- non-deterministic (logic) programming, concurrent programming and functional
1664-- reactive programming. In other words, you can do everything with this one
1665-- abstraction that you could do with the popular libraries listed under these
1666-- categories in the list below.
1669-- +-----------------+----------------+
1670-- | Non-determinism | <https://hackage.haskell.org/package/pipes pipes> |
1671-- | +----------------+
1672-- | | <https://hackage.haskell.org/package/list-t list-t> |
1673-- | +----------------+
1674-- | | <https://hackage.haskell.org/package/logict logict> |
1675-- +-----------------+----------------+
1676-- | Streaming | <https://hackage.haskell.org/package/vector vector> |
1677-- | +----------------+
1678-- | | <https://hackage.haskell.org/package/streaming streaming> |
1679-- | +----------------+
1680-- | | <https://hackage.haskell.org/package/pipes pipes> |
1681-- | +----------------+
1682-- | | <https://hackage.haskell.org/package/conduit conduit> |
1683-- +-----------------+----------------+
1684-- | Concurrency | <https://hackage.haskell.org/package/async async> |
1685-- | +----------------+
1686-- | | <https://hackage.haskell.org/package/transient transient> |
1687-- +-----------------+----------------+
1688-- | FRP | <https://hackage.haskell.org/package/Yampa Yampa> |
1689-- | +----------------+
1690-- | | <https://hackage.haskell.org/package/dunai dunai> |
1691-- | +----------------+
1692-- | | <https://hackage.haskell.org/package/reflex reflex> |
1693-- +-----------------+----------------+
1696-- Streamly is a list-transformer. It provides all the functionality provided
1697-- by any of the list transformer and logic programming packages listed above.
1698-- In addition, Streamly naturally integrates the concurrency dimension to the
1699-- basic list transformer functionality.
1701-- When it comes to streaming, in terms of the streaming API streamly is almost
1702-- identical to the vector package. Streamly, vector and streaming packages all
1703-- represent a stream as data and are therefore similar in the fundamental
1704-- approach to streaming. The fundamental difference is that streamly adds
1705-- concurrency support and the monad instance provides concurrent looping.
1706-- Other streaming libraries like pipes, conduit and machines represent and
1707-- compose stream processors rather than the stream data and therefore fall in
1708-- another class of streaming libraries and have comparatively more complicated
1711-- When it comes to concurrency, streamly can do everything that the @async@
1712-- package can do and more. async provides applicative concurrency whereas
1713-- streamly provides both applicative and monadic concurrency. The
1714-- 'ZipAsync' type behaves like the applicative instance of async. In
1715-- comparison to transient streamly has a first class streaming interface and
1716-- is a monad transformer that can be used universally in any Haskell monad
1717-- transformer stack. Streamly was in fact originally inspired by the
1718-- concurrency implementation in @transient@ though it has no resemblance with
1719-- that and takes a lazy pull approach versus transient's strict push approach.
1721-- The non-determinism, concurrency and streaming combination make streamly a
1722-- strong reactive programming library as well. Reactive programming is
1723-- fundamentally stream of events that can be processed concurrently. The
1724-- example in this tutorial as well as the
1725-- <examples/CirclingSquare.hs CirclingSquare> example from Yampa demonstrate
1726-- the basic reactive capability of streamly. In core concepts streamly is
1727-- strikingly similar to @dunai@. dunai was designed from a FRP perspective
1728-- and streamly was originally designed from a concurrency perspective.
1729-- However, both have similarity at the core.
1733-- * Read the documentation of "Streamly" module
1734-- * Read the documentation of "Streamly.Prelude" module
1735-- * See the examples in the "examples" directory of the package
1736-- * See the tests in the "test" directory of the package
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