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 streaming IO. The IO
10-- monad and pure lists are a special case of streamly. On one hand, streamly
11-- extends the lists of pure values to lists of monadic actions, on the other
12-- hand it extends the IO monad with concurrrent non-determinism. In simple
13-- imperative terms we can say that streamly extends the IO monad with @for@
14-- loops and nested @for@ loops with concurrency support. You can understand
15-- this analogy better once you can go through this tutorial.
17-- Streaming in general enables writing modular, composable and scalable
18-- applications with ease, and concurrency allows you to make them scale and
19-- perform well. Streamly enables writing scalable concurrent applications
20-- without being aware of threads or synchronization. No explicit thread
21-- control is needed, where applicable the concurrency rate is automatically
22-- controlled based on the demand by the consumer. However, combinators can be
23-- used to fine tune the concurrency control.
25-- Streaming and concurrency together enable expressing reactive applications
26-- conveniently. See the @CirclingSquare@ example in the examples directory for
27-- a simple SDL based FRP example. To summarize, streamly provides a unified
28-- computing framework for streaming, non-determinism and functional reactive
29-- programming in an elegant and simple API that is a natural extension of pure
30-- lists to monadic streams.
32-- In this tutorial we will go over the basic concepts and how to
33-- use the library. See the last section for further reading resources.
35module Streamly.Tutorial
40 -- * Flavors of Streams
43 -- * Imports and Supporting Code
46 -- * Generating Streams
49 -- * Eliminating Streams
52 -- * Transforming Streams
60 -- *** Deep Serial Composition ('Serial')
63 -- *** Wide Serial Composition ('WSerial')
66 -- *** Deep Asynchronous Composition ('Async')
69 -- *** Wide Asynchronous Composition ('WAsync')
72 -- *** Parallel Asynchronous Composition ('Parallel')
75 -- *** Custom composition
87 -- *** Deep Serial Nesting ('Serial')
90 -- *** Wide Serial Nesting ('WSerial')
91 -- $interleavedNesting
93 -- *** Deep Asynchronous Nesting ('Async')
96 -- *** Wide Asynchronous Nesting ('WAsync')
99 -- *** Parallel Asynchronous Nesting ('Parallel')
117 -- ** Parallel Zipping
120 -- * Monad transformers
121 -- $monadtransformers
123 -- * Concurrent Programming
126 -- * Reactive Programming
132 -- * Interoperation with Streaming Libraries
135 -- * Comparison with Existing Packages
138 -- * Where to go next?
144import Streamly.Prelude
146import Control.Applicative
148import Control.Monad.IO.Class (MonadIO(..))
149import Control.Monad.Trans.Class (MonadTrans (lift))
153-- The way a list represents a sequence of pure values, a stream represents a
154-- sequence of monadic actions. The monadic stream API offered by Streamly is
155-- very close to the Haskell "Prelude" pure lists' API, it can be considered as a
156-- natural extension of lists to monadic actions. Streamly streams provide
157-- concurrent composition and merging of streams. It can be considered as a
158-- concurrent list transformer. In contrast to the "Prelude" lists, merging or
159-- appending streams of arbitrary length is scalable and inexpensive.
161-- The basic stream type is 'Serial', it represents a sequence of IO actions,
162-- and is a 'Monad'. The 'Serial' monad is almost a drop in replacement for
163-- the 'IO' monad, IO monad is a special case of the 'Serial' monad; IO monad
164-- represents a single IO action whereas the 'Serial' monad represents a series
165-- of IO actions. The only change you need to make to go from 'IO' to 'Serial'
166-- is to use 'runStream' to run the monad and to prefix the IO actions with
167-- either 'once' or 'liftIO'. If you use liftIO you can switch from 'Serial'
168-- to IO monad by simply removing the 'runStream' function; no other changes
169-- are needed unless you have used some stream specific composition or
172-- Similarly, the 'Serial' type is almost a drop in replacement for pure lists,
173-- pure lists are a special case of monadic streams. If you use 'nil' in place
174-- of '[]' and '|:' in place ':' you can replace a list with a 'Serial' The
175-- only difference is that the elements must be monadic type and to operate on
176-- the streams we must use the corresponding functions from "Streamly.Prelude"
177-- instead of using the base "Prelude".
181-- There are a few more types similar to 'Serial' that all represent streams
182-- and differ only in the 'Semigroup', 'Applicative' and 'Monad' compositions
185-- The composition of two or more streams is distinguished based on three
186-- characterstics, /traversal order/, /execution order/ and
187-- /consumption order/. Traversal of a composition of streams could be @deep@
188-- or @wide@. Deep goes depth first i.e. each stream is traversed fully
189-- before we traverse the next stream. Wide goes breadth first i.e. one element
190-- from each stream is traversed before coming back to the first stream again.
191-- Execution could be serial (i.e. synchronous) or asynchronous. In serial
192-- execution we execute an action in the next stream only after the first has
193-- finished executing. In asynchronous execution actions in both streams can be
194-- executed asynchronously i.e. the next action can start executing even before
195-- the first one has finished. The third parameter is consumption order that is
196-- in what order the output generated by the composition is consumed.
197-- Consumption could be serial or asynchronous. In serial consumption, the
198-- outputs are consumed in the traversal order, in asynchronous consumption the
199-- outputs are consumed as they arrive i.e. first come first serve order.
201-- The following table summarizes different styles of streams based on how they
202-- compose. All these types are monads and they differ in 'Semigroup',
203-- 'Applicative' and 'Monad' compositions:
206-- +------------+-----------+--------------+--------------+
207-- | Type | Traversal | Execution | Consumption |
208-- +============+===========+==============+==============+
209-- | 'Serial' | Deep | Serial | Serial |
210-- +------------+-----------+--------------+--------------+
211-- | 'WSerial' | Wide | Serial | Serial |
212-- +------------+-----------+--------------+--------------+
213-- | 'Async' | Deep | Asynchronous | Asynchronous |
214-- +------------+-----------+--------------+--------------+
215-- | 'WAsync' | Wide | Asynchronous | Asynchronous |
216-- +------------+-----------+--------------+--------------+
217-- | 'Parallel' | Parallel | Asynchronous | Asynchronous |
218-- +------------+-----------+--------------+--------------+
221-- Other than these types there are also 'ZipSerial' and 'ZipAsync' types that
222-- zip streams serially or concurrently using 'Applicative' operation. These
223-- types are not monads they are only applicatives and they do not differ in
224-- 'Semigroup' composition.
226-- All these types can be freely inter-converted using type conversion
227-- combinators or type annotations without any cost, to acheive the desired
228-- composition style. To force a particular type of composition we coerce the
229-- stream type using the corresponding type adapting combinator from
230-- 'serially', 'wSerially', 'asyncly', 'wAsyncly', 'parallely', 'zipSerially'
231-- or 'zipAsyncly'. The default stream type is inferred as 'Serial' unless you
232-- change it by using one of the combinators or using a type annotation.
236-- To represent streams in an arbitrary monad use the more general monad
237-- transformer types for example the monad transformer type corresponding to
238-- the 'Serial' type is 'SerialT'. @SerialT m a@ represents a stream of values
239-- of type 'a' in some underlying monad 'm'. For example, @SerialT IO Int@ is a
240-- stream of 'Int' in 'IO' monad. In fact, the type 'Serial' is a synonym for
243-- Similarly we have monad transformer types for other stream types as well viz.
244-- 'WSerialT', 'AsyncT', 'WAsyncT' and 'ParallelT'.
246-- To lift a value from an underlying monad in a monad transformer stack into a
247-- singleton stream use 'lift' and to lift from an IO action use 'liftIO'.
250-- > 'runStream' $ liftIO $ putStrLn "Hello world!"
252-- > 'runStream' $ lift $ putStrLn "Hello world!"
259-- We will assume the following imports in this tutorial. Go ahead, fire up a
260-- GHCi session and import these lines to start playing.
263-- > import "Streamly"
264-- > import "Streamly.Prelude" ((|:))
265-- > import qualified "Streamly.Prelude" as S
268-- 'nil' represents an empty stream and 'consM' or its operator form '|:' adds
269-- a monadic action at the head of the stream.
272-- > S.'toList' S.'nil'
274-- > S.'toList' $ 'getLine' |: 'getLine' |: S.'nil'
280-- To create a singleton stream from a pure value use 'pure' and to create a
281-- singleton stream from a monadic action use 'once'.
284-- > S.'toList' $ 'pure' 1
286-- > S.'toList' $ S.'once' 'getLine'
291-- To create a stream from pure values in a 'Foldable' container use
292-- 'fromFoldable' which is equivalent to a fold using 'cons' and 'nil':
295-- > S.'toList' $ S.'fromFoldable' [1..3]
297-- > S.'toList' $ 'Prelude.foldr' S.'cons' S.'nil' [1..3]
301-- To create a stream from monadic actions in a 'Foldable' container just use a
302-- right fold using 'consM' and 'nil':
305-- > 'runStream' $ 'Prelude.foldr' ('|:') S.'nil' ['putStr' "Hello ", 'putStrLn' "world!"]
309-- For more ways to construct a stream see the module "Streamly.Prelude".
313-- We have already seen 'runStream' and 'toList' to eliminate a stream in the
314-- examples above. 'runStream' runs a stream discarding the results i.e. only
315-- for effects. 'toList' runs the stream and collects the results in a list.
317-- For other ways to eliminate a stream see the @Folding@ section in
318-- "Streamly.Prelude" module.
322-- Transformation over a stream is the equivalent of a @for@ loop construct in
323-- imperative paradigm. We iterate over every element in the stream and perform
324-- certain transformations for each element. Transformations may involve
325-- mapping functions over the elements, filtering elements from the stream or
326-- folding all the elements in the stream into a single value. Streamly streams
327-- are exactly like lists and you can perform all the transformations in the
328-- same way as you would on lists.
330-- Here is a simple console echo program that just echoes every input line,
334-- > 'runStream' $ S.'repeatM' getLine & S.'mapM' putStrLn
337-- The following code snippet reads lines from standard input, filters blank
338-- lines, drops the first non-blank line, takes the next two, up cases them,
339-- numbers them and prints them:
343-- import qualified "Streamly.Prelude" as S
344-- import Data.Char (toUpper)
345-- import Data.Function ((&))
347-- main = 'runStream' $
348-- S.'repeatM' getLine
349-- & S.'filter' (not . null)
352-- & fmap (map toUpper)
353-- & S.'zipWith' (\\n s -> show n ++ " " ++ s) (S.'fromFoldable' [1..])
354-- & S.'mapM' putStrLn
359-- We can combine two streams into a single stream using semigroup composition
360-- operation '<>'. Streams can be combined in many different ways as described
361-- in the following sections, the '<>' operation behaves differently depending
362-- on the stream type in effect. The stream type and therefore the composition
363-- style can be changed at any point using one of the type combinators as
368-- In most of example snippets we do not repeat the imports. Where imports are
369-- not explicitly specified use the imports shown below.
373-- import "Streamly.Prelude" ((|:), nil)
374-- import qualified "Streamly.Prelude" as S
376-- import Control.Concurrent
377-- import Control.Monad (forever)
380-- To illustrate concurrent vs serial composition aspects, we will use the
381-- following @delay@ function to introduce a sleep or delay specified in
382-- seconds. After the delay it prints the number of seconds it slept.
385-- delay n = S.'once' $ do
386-- threadDelay (n * 1000000)
388-- putStrLn (show tid ++ ": Delay " ++ show n)
393-- The 'Semigroup' operation '<>' of the 'Serial' type combines the two streams
394-- in a /serial depth first/ manner. We use the 'serially' type combinator to
395-- effect 'Serial' style of composition. We can also use an explicit 'Serial'
396-- type annotation for the stream to acheive the same effect. However, since
397-- 'Serial' is the default type unless explicitly specified by using a
398-- combinator, we can omit using an explicit combinator or type annotation for
399-- this style of composition.
401-- When two streams with multiple elements are combined in this manner, the
402-- monadic actions in the two streams are performed sequentially i.e. first all
403-- actions in the first stream are performed sequentially and then all actions
404-- in the second stream are performed sequentially. We call it
405-- /serial depth first/ as the full depth of one stream is fully traversed
406-- before we move to the next. The following example prints the sequence 1, 2,
410-- main = 'runStream' $ (print 1 |: print 2 |: nil) <> (print 3 |: print 4 |: nil)
419-- All actions in both the streams are performed serially in the same thread.
420-- In the following example we can see that all actions are performed in the
421-- same thread and take a combined total of @3 + 2 + 1 = 6@ seconds:
424-- main = 'runStream' $ delay 3 <> delay 2 <> delay 1
427-- ThreadId 36: Delay 3
428-- ThreadId 36: Delay 2
429-- ThreadId 36: Delay 1
432-- The polymorphic version of the binary operation '<>' of the 'Serial' type is
433-- 'serial'. We can use 'serial' to join streams in a sequential manner
434-- irrespective of the type of stream:
437-- main = 'runStream' $ (print 1 |: print 2 |: nil) \`serial` (print 3 |: print 4 |: nil)
442-- The 'Semigroup' operation '<>' of the 'WSerial' type combines the two
443-- streams in a /serial breadth first/ manner. We use the 'wSerially' type
444-- combinator to effect 'WSerial' style of composition. We can also use the
445-- 'WSerial' type annotation for the stream to acheive the same effect.
447-- When two streams with multiple elements are combined in this manner, we
448-- traverse all the streams in a breadth first manner i.e. one action from each
449-- stream is peformed and yielded to the resulting stream before we come back
450-- to the first stream again and so on.
451-- The following example prints the sequence 1, 3, 2, 4
454-- main = 'runStream' . 'wSerially' $ (print 1 |: print 2 |: nil) <> (print 3 |: print 4 |: nil)
463-- Even though the monadic actions of the two streams are performed in an
464-- interleaved manner they are all performed serially in the same thread. In
465-- the following example we can see that all actions are performed in the same
466-- thread and take a combined total of @3 + 2 + 1 = 6@ seconds:
469-- main = 'runStream' . 'wSerially' $ delay 3 <> delay 2 <> delay 1
472-- ThreadId 36: Delay 3
473-- ThreadId 36: Delay 2
474-- ThreadId 36: Delay 1
477-- The polymorphic version of the 'WSerial' binary operation '<>' is called
478-- 'wSerial'. We can use 'wSerial' to join streams in an interleaved manner
479-- irrespective of the type, notice that we have not used the 'wSerially'
480-- combinator in the following example:
483-- main = 'runStream' $ (print 1 |: print 2 |: nil) \`wSerial` (print 3 |: print 4 |: nil)
492-- Note that this composition cannot be used to fold infinite number of streams
493-- since it requires preserving the state until a stream is finished.
497-- The 'Semigroup' operation '<>' of the 'Async' type combines the two
498-- streams in a depth first manner with parallel look ahead. We use the
499-- 'asyncly' type combinator to effect 'Async' style of composition. We
500-- can also use the 'Async' type annotation for the stream type to acheive
503-- When two streams with multiple elements are combined in this manner, the
504-- streams are traversed in depth first manner just like 'Serial', however it
505-- can execute the next stream concurrently and return the results from it
506-- as they arrive i.e. the results from the next stream may be yielded even
507-- before the results from the first stream. Concurrent execution of the next
508-- stream(s) is performed if the first stream blocks or if it cannot produce
509-- output at the rate that is enough to meet the consumer demand. Multiple
510-- streams can be executed concurrently to meet the demand.
511-- In the following example the first stream does not block,
512-- therefore the first stream is completely exhausted before the second.
515-- main = 'runStream' . 'asyncly' $ (print 1 |: print 2 |: nil) <> (print 3 |: print 4 |: nil)
524-- If the first stream blocks, we can yield from the second. In the example
525-- below each yield in the stream has a constant delay of 1 second therefore 1
526-- and 3 would be yielded first and then 2 and 4 would be yielded.
529-- main = 'runStream' . 'asyncly' $ (p 1 |: p 2 |: nil) <> (p 3 |: p 4 |: nil)
530-- where p n = threadDelay 1000000 >> print n
539-- In the following example we can see that new threads are started when a
540-- computation blocks. Notice that the output from the stream with the
541-- shortest delay is printed first. The whole computation takes @maximum of
542-- (3, 2, 1) = 3@ seconds:
545-- main = 'runStream' . 'asyncly' $ delay 3 '<>' delay 2 '<>' delay 1
548-- ThreadId 42: Delay 1
549-- ThreadId 41: Delay 2
550-- ThreadId 40: Delay 3
553-- When we have a tree of computations composed using this style, the tree is
554-- traversed in DFS style just like the 'Serial' style, the only difference is
555-- that here we can move on to executing the next stream if a stream blocks.
556-- However, we will not start new threads if we have sufficient output to
557-- saturate the consumer. This is why we call it left-biased demand driven or
558-- adaptive concurrency style, the concurrency tends to stay on the left side
559-- of the composition as long as possible. More threads are started based on
560-- the pull rate of the consumer. The following example prints an output every
561-- second as all of the actions are concurrent.
564-- main = 'runStream' . 'asyncly' $ (delay 1 <> delay 2) <> (delay 3 <> delay 4)
573-- All the computations may even run in a single thread when more threads are
574-- not needed. As you can see, in the following example the computations are
575-- run in a single thread one after another, because none of them blocks.
576-- However, if the thread consuming the stream were faster than the producer
577-- then it would have started parallel threads for each computation to keep up
578-- even if none of them blocks:
581-- main = 'runStream' . 'asyncly' $ traced (sqrt 9) '<>' traced (sqrt 16) '<>' traced (sqrt 25)
582-- where traced m = S.'once' (myThreadId >>= print) >> return m
590-- Note that the order of printing in the above examples may change due to
591-- variations in scheduling latencies for concurrent threads.
593-- The polymorphic version of the 'Async' binary operation '<>' is called
594-- 'async'. We can use 'async' to join streams in a left biased
595-- adaptively concurrent manner irrespective of the type, notice that we have
596-- not used the 'asyncly' combinator in the following example:
599-- main = 'runStream' $ delay 3 \`async` delay 2 \`async` delay 1
602-- ThreadId 42: Delay 1
603-- ThreadId 41: Delay 2
604-- ThreadId 40: Delay 3
607-- Since the concurrency provided by this operator is demand driven it cannot
608-- be used when the composed computations start timers that are relative to
609-- each other because all computations may not be started at the same time and
610-- therefore timers in all of them may not start at the same time. When
611-- relative timing among all computations is important or when we need to start
612-- all computations at once for any reason 'Parallel' style must be used
615-- 'Async' style should be preferred over 'Parallel' or 'WAsync' unless you
616-- really need those. It utilizes the resources optimally. It should be used
617-- when we know that the computations can run in parallel but we do not care if
618-- they actually run in parallel or not, that decision can be left to the
619-- scheduler based on demand. Also, note that this operator can be used to fold
620-- infinite number of streams in contrast to the 'Parallel' or 'WAsync' styles,
621-- because it does not require us to run all of them at the same time in a fair
626-- The 'Semigroup' operation '<>' of the 'WAsync' type combines two streams in
627-- a concurrent manner using /breadth first traversal/. We use the 'wAsyncly'
628-- type combinator to effect 'WAsync' style of composition. We can also use the
629-- 'WAsync' type annotation for the stream to acheive the same effect.
631-- When streams with multiple elements are combined in this manner, we traverse
632-- all the streams concurrently in a breadth first manner i.e. one action from
633-- each stream is peformed and yielded to the resulting stream before we come
634-- back to the first stream again and so on. Even though we execute the actions
635-- in a breadth first order the outputs may be consumed in a different order
636-- because they are consumed on a first come first serve basis.
638-- In the following example we can see that outputs are produced in the breadth
639-- first travresal order but this is not guaranteed.
642-- main = 'runStream' . 'wAsyncly' $ (print 1 |: print 2 |: nil) <> (print 3 |: print 4 |: nil)
651-- The polymorphic version of the binary operation '<>' of the 'WAsync' type is
652-- 'wAsync'. We can use 'wAsync' to join streams using a breadth first
653-- concurrent traversal irrespective of the type, notice that we have not used
654-- the 'wAsyncly' combinator in the following example:
657-- main = 'runStream' $ delay 3 \`wAsync` delay 2 \`wAsync` delay 1
660-- ThreadId 42: Delay 1
661-- ThreadId 41: Delay 2
662-- ThreadId 40: Delay 3
665-- Since the concurrency provided by this style is demand driven it may not
666-- be used when the composed computations start timers that are relative to
667-- each other because all computations may not be started at the same time and
668-- therefore timers in all of them may not start at the same time. When
669-- relative timing among all computations is important or when we need to start
670-- all computations at once for any reason 'Parallel' style must be used
676-- The 'Semigroup' operation '<>' of the 'Parallel' type combines the two
677-- streams in a fairly concurrent manner with round robin scheduling. We use
678-- the 'parallely' type combinator to effect 'Parallel' style of composition.
679-- We can also use the 'Parallel' type annotation for the stream type to
680-- acheive the same effect.
682-- When two streams with multiple elements are combined in this manner, the
683-- monadic actions in both the streams are performed concurrently with a fair
684-- round robin scheduling. The outputs are yielded in the order in which the
685-- actions complete. This is pretty similar to the 'WAsync' type, the
686-- difference is that 'WAsync' is adaptive to the consumer demand and may or
687-- may not execute all actions in parallel depending on the demand, whereas
688-- 'Parallel' runs all the streams in parallel irrespective of the demand.
690-- The following example sends a query to all the three search engines in
691-- parallel and prints the name of the search engines in the order in which the
696-- import qualified Streamly.Prelude as S
697-- import Network.HTTP.Simple
699-- main = 'runStream' . 'parallely' $ google \<> bing \<> duckduckgo
701-- google = get "https://www.google.com/search?q=haskell"
702-- bing = get "https://www.bing.com/search?q=haskell"
703-- duckduckgo = get "https://www.duckduckgo.com/?q=haskell"
704-- get s = S.'once' (httpNoBody (parseRequest_ s) >> putStrLn (show s))
707-- The polymorphic version of the binary operation '<>' of the 'Parallel' type
708-- is 'parallel'. We can use 'parallel' to join streams in a fairly concurrent
709-- manner irrespective of the type, notice that we have not used the
710-- 'parallely' combinator in the following example:
713-- main = 'runStream' $ delay 3 \`parallel` delay 2 \`wAsync` delay 1
716-- ThreadId 42: Delay 1
717-- ThreadId 41: Delay 2
718-- ThreadId 40: Delay 3
721-- Note that this style of composition cannot be used to combine infinite
722-- number of streams, as it will lead to an infinite sized scheduling queue.
727-- The 'mkAsync' API can be used to create references to asynchronously running
728-- stream computations. We can then use 'uncons' to explore the streams
729-- arbitrarily and then recompose individual elements to create a new stream.
730-- This way we can dynamically decide which stream to explore at any given
731-- time. Take an example of a merge sort of two sorted streams. We need to
732-- keep consuming items from the stream which has the lowest item in the sort
733-- order. This can be achieved using async references to streams. See
734-- "MergeSort.hs" in the examples directory.
738-- We can use 'Monoid' instances to fold a container of streams in the desired
739-- style using 'fold' or 'foldMap'. We have also provided some fold utilities
740-- to fold streams using the polymorphic combine operations:
742-- * 'foldWith' is like 'fold', it folds a 'Foldable' container of streams
743-- using the given composition operator.
744-- * 'foldMapWith' is like 'foldMap', it folds like @foldWith@ but also maps a
745-- function before folding.
746-- * 'forEachWith' is like @foldMapwith@ but the container argument comes before
747-- the function argument.
749-- All of the following are equivalent and start ten concurrent tasks each with
750-- a delay from 1 to 10 seconds, resulting in the printing of each number every
755-- import qualified "Streamly.Prelude" as S
756-- import Control.Concurrent
759-- 'runStream' $ 'asyncly' $ foldMap delay [1..10]
760-- 'runStream' $ 'foldWith' 'async' (map delay [1..10])
761-- 'runStream' $ 'foldMapWith' 'async' delay [1..10]
762-- 'runStream' $ 'forEachWith' 'async' [1..10] delay
763-- where delay n = S.'once' $ threadDelay (n * 1000000) >> print n
768-- Till now we discussed ways to apply transformations on a stream or to merge
769-- streams together to create another stream. We mentioned earlier that
770-- transforming a stream is similar to a @for@ loop in the imperative paradigm.
771-- We will now discuss the concept of a nested composition of streams which is
772-- analogous to nested @for@ loops in the imperative paradigm. Functional
773-- programmers call this style of composition a list transformer or @ListT@.
774-- Logic programmers call it a logic monad or non-deterministic composition,
775-- but for ordinary imperative minded people like me it is easier to think in
776-- terms of good old nested @for@ loops.
780-- In functional programmer's parlance the 'Monad' instances of different
781-- 'IsStream' types implement non-determinism, exploring all possible
782-- combination of choices from both the streams. From an imperative
783-- programmer's point of view it behaves like nested loops i.e. for each
784-- element in the first stream and for each element in the second stream
785-- execute the body of the loop.
787-- The 'Monad' instances of 'Serial', 'WSerial', 'Async' and 'WAsync'
788-- stream types support different flavors of nested looping. In other words,
789-- they are all variants of list transformer. The nesting behavior of these
790-- types correspond exactly to the way they merge streams as we discussed in
791-- the previous section.
796-- The 'Monad' composition of the 'Serial' type behaves like a standard list
797-- transformer. This is the default when we do not use an explicit type
798-- combinator. However, the 'serially' type combinator can be used to switch to
799-- this style of composition. We will see how this style of composition works
800-- in the following examples.
802-- Let's start with an example with a simple @for@ loop without any nesting.
803-- For simplicity of illustration we are using streams of pure values in all
804-- the examples. However, the streams could also be made of monadic actions
809-- import qualified "Streamly.Prelude" as S
811-- main = 'runStream' $ do
812-- x <- S.'fromFoldable' [3,2,1]
816-- ThreadId 30: Delay 3
817-- ThreadId 30: Delay 2
818-- ThreadId 30: Delay 1
821-- As we can see, the code after the @fromFoldable@ statement is run three
822-- times, once for each value of @x@ drawn from the stream. All the three
823-- iterations are serial and run in the same thread one after another. In
824-- imperative terms this is equivalent to a @for@ loop with three iterations.
826-- A console echo loop copying standard input to standard output can simply be
831-- import qualified "Streamly.Prelude" as S
833-- main = 'runStream' $ forever $ S.once getLine >>= S.once . putStrLn
836-- When multiple streams are composed using this style they nest in a DFS
837-- manner i.e. nested iterations of a loop are executed before we proceed to
838-- the next iteration of the parent loop. This behaves just like nested @for@
839-- loops in imperative programming.
843-- import qualified "Streamly.Prelude" as S
845-- main = 'runStream' $ do
846-- x <- S.'fromFoldable' [1,2]
847-- y <- S.'fromFoldable' [3,4]
848-- S.'once' $ putStrLn $ show (x, y)
857-- Notice that this is analogous to merging streams of type 'Serial' or merging
858-- streams using 'serial'.
862-- The 'Monad' composition of 'Async' type can perform the iterations of a
863-- loop concurrently. Concurrency is demand driven i.e. more concurrent
864-- iterations are started only if the previous iterations are not able to
865-- produce enough output for the consumer of the output stream. This works
866-- exactly the same way as the merging of two streams 'asyncly' works.
867-- This is the concurrent analogue of 'Serial' style monadic composition.
869-- The 'asyncly' type combinator can be used to switch to this style of
870-- composition. Alternatively, a type annotation can be used to specify the
871-- type of the stream as 'Async'.
875-- import "Streamly.Prelude"
877-- main = 'runStream' . 'asyncly' $ do
878-- x <- S.'fromFoldable' [3,2,1]
882-- ThreadId 40: Delay 1
883-- ThreadId 39: Delay 2
884-- ThreadId 38: Delay 3
887-- As we can see the code after the @fromFoldable@ statement is run three
888-- times, once for each value of @x@. All the three iterations are concurrent
889-- and run in different threads. The iteration with least delay finishes first.
890-- When compared to imperative programming, this can be viewed as a @for@ loop
891-- with three concurrent iterations.
893-- Concurrency is demand driven just as in the case of 'async' merging.
894-- When multiple streams are composed using this style, the iterations are
895-- triggered in a depth first manner just like 'Serial' i.e. nested iterations are
896-- executed before we proceed to the next iteration at higher level. However,
897-- unlike 'Serial' more than one iterations may be started concurrently based
898-- on the demand from the consumer of the stream.
902-- import qualified "Streamly.Prelude" as S
904-- main = 'runStream' . 'asyncly' $ do
905-- x <- S.'fromFoldable' [1,2]
906-- y <- S.'fromFoldable' [3,4]
907-- S.'once' $ putStrLn $ show (x, y)
916-- $interleavedNesting
918-- The 'Monad' composition of 'WSerial' type interleaves the iterations of
919-- outer and inner loops in a nested loop composition. This works exactly the
920-- same way as the merging of two streams in 'wSerially' fashion works. The
921-- 'wSerially' type combinator can be used to switch to this style of
922-- composition. Alternatively, a type annotation can be used to specify the
923-- type of the stream as 'WSerial'.
927-- import qualified "Streamly.Prelude" as S
929-- main = 'runStream' . 'wSerially' $ do
930-- x <- S.'fromFoldable' [1,2]
931-- y <- S.'fromFoldable' [3,4]
932-- S.once $ putStrLn $ show (x, y)
944-- Just like 'Async' the 'Monad' composition of 'WAsync' runs the iterations of
945-- a loop concurrently. The difference is in the nested loop behavior. The
946-- nested loops in this type are traversed and executed in a breadth first
947-- manner rather than the depth first manner of 'Async' style.
948-- The loop nesting works exactly the same way as the merging of streams
949-- 'wAsyncly' works. The 'wAsyncly' type combinator can be used to switch to
950-- this style of composition. Alternatively, a type annotation can be used to
951-- specify the type of the stream as 'WAsync'.
955-- import qualified "Streamly.Prelude" as S
957-- main = 'runStream' . 'wAsyncly' $ do
958-- x <- S.'fromFoldable' [1,2]
959-- y <- S.'fromFoldable' [3,4]
960-- S.'once' $ putStrLn $ show (x, y)
971-- Just like 'Async' or 'WAsync' the 'Monad' composition of 'Parallel' runs the
972-- iterations of a loop concurrently. The difference is in the nested loop
973-- behavior. The streams at each nest level is run fully concurrently
974-- irrespective of the demand. The loop nesting works exactly the same way as
975-- the merging of streams 'parallely' works. The 'parallely' type combinator
976-- can be used to switch to this style of composition. Alternatively, a type
977-- annotation can be used to specify the type of the stream as 'Parallel'.
981-- import qualified "Streamly.Prelude" as S
983-- main = 'runStream' . 'parallely' $ do
984-- x <- S.'fromFoldable' [3,2,1]
988-- ThreadId 40: Delay 1
989-- ThreadId 39: Delay 2
990-- ThreadId 38: Delay 3
995-- Streamly code is usually written in a way that is agnostic of the
996-- specific monadic composition type. We use a polymorphic type with a
997-- 'IsStream' type class constraint. When running the stream we can choose the
998-- specific mode of composition. For example take a look at the following code.
1002-- import qualified "Streamly.Prelude" as S
1004-- composed :: (IsStream t, Monad (t IO)) => t IO ()
1009-- S.'once' $ putStrLn $ show (sz, cl, sh)
1013-- sizes = S.'fromFoldable' [1, 2, 3]
1014-- colors = S.'fromFoldable' ["red", "green", "blue"]
1015-- shapes = S.'fromFoldable' ["triangle", "square", "circle"]
1018-- Now we can interpret this in whatever way we want:
1021-- main = 'runStream' . 'serially' $ composed
1022-- main = 'runStream' . 'wSerially' $ composed
1023-- main = 'runStream' . 'asyncly' $ composed
1024-- main = 'runStream' . 'wAsyncly' $ composed
1025-- main = 'runStream' . 'parallely' $ composed
1028-- As an exercise try to figure out the output of this code for each mode of
1033-- 'fmap' transforms a stream by mapping a function on all elements of the
1034-- stream. 'fmap' behaves in the same way for all stream types, it is always
1039-- import qualified "Streamly.Prelude" as S
1041-- main = (S.'toList' $ fmap show $ S.'fromFoldable' [1..10]) >>= print
1044-- Also see the 'mapM' and 'sequence' functions for mapping actions, in the
1045-- "Streamly.Prelude" module.
1049-- Applicative is precisely the same as the 'ap' operation of 'Monad'. For
1050-- zipping applicatives separate types 'ZipSerial' and 'ZipAsync' are
1053-- The following example uses the 'Serial' applicative, it runs all iterations
1054-- serially and takes a total 17 seconds (1 + 3 + 4 + 2 + 3 + 4):
1058-- import qualified "Streamly.Prelude" as S
1059-- import Control.Concurrent
1063-- d n = delay n >> return n
1065-- main = (S.'toList' . 'serially' $ (,) \<$> s1 \<*> s2) >>= print
1068-- ThreadId 36: Delay 1
1069-- ThreadId 36: Delay 3
1070-- ThreadId 36: Delay 4
1071-- ThreadId 36: Delay 2
1072-- ThreadId 36: Delay 3
1073-- ThreadId 36: Delay 4
1074-- [(1,3),(1,4),(2,3),(2,4)]
1077-- Similalrly 'WSerial' applicative runs the iterations in an interleaved
1078-- order but since it is serial it takes a total of 17 seconds:
1081-- main = (S.'toList' . 'wSerially' $ (,) \<$> s1 \<*> s2) >>= print
1084-- ThreadId 36: Delay 1
1085-- ThreadId 36: Delay 3
1086-- ThreadId 36: Delay 2
1087-- ThreadId 36: Delay 3
1088-- ThreadId 36: Delay 4
1089-- ThreadId 36: Delay 4
1090-- [(1,3),(2,3),(1,4),(2,4)]
1093-- 'Async' can run the iterations concurrently and therefore takes a total
1094-- of 10 seconds (1 + 2 + 3 + 4):
1097-- main = (S.'toList' . 'asyncly' $ (,) \<$> s1 \<*> s2) >>= print
1100-- ThreadId 34: Delay 1
1101-- ThreadId 36: Delay 2
1102-- ThreadId 35: Delay 3
1103-- ThreadId 36: Delay 3
1104-- ThreadId 35: Delay 4
1105-- ThreadId 36: Delay 4
1106-- [(1,3),(2,3),(1,4),(2,4)]
1109-- Similalrly 'WAsync' as well can run the iterations concurrently and
1110-- therefore takes a total of 10 seconds (1 + 2 + 3 + 4):
1113-- main = (S.'toList' . 'wAsyncly' $ (,) \<$> s1 \<*> s2) >>= print
1116-- ThreadId 34: Delay 1
1117-- ThreadId 36: Delay 2
1118-- ThreadId 35: Delay 3
1119-- ThreadId 36: Delay 3
1120-- ThreadId 35: Delay 4
1121-- ThreadId 36: Delay 4
1122-- [(1,3),(2,3),(1,4),(2,4)]
1127-- Zipping is a special transformation where the corresponding elements of two
1128-- streams are combined together using a zip function producing a new stream of
1129-- outputs. Two different types are provided for serial and concurrent zipping.
1130-- These types provide an applicative instance that can be used to lift
1131-- functions to zip the argument streams.
1132-- Also see the zipping functions in the "Streamly.Prelude" module.
1136-- The applicative instance of 'ZipSerial' type zips streams serially.
1137-- 'zipSerially' type combinator can be used to switch to serial applicative
1142-- import qualified "Streamly.Prelude" as S
1143-- import Control.Concurrent
1145-- d n = delay n >> return n
1146-- s1 = 'serially' $ d 1 <> d 2
1147-- s2 = 'serially' $ d 3 <> d 4
1149-- main = (S.'toList' . 'zipSerially' $ (,) \<$> s1 \<*> s2) >>= print
1152-- This takes total 10 seconds to zip, which is (1 + 2 + 3 + 4) since
1153-- everything runs serially:
1156-- ThreadId 29: Delay 1
1157-- ThreadId 29: Delay 3
1158-- ThreadId 29: Delay 2
1159-- ThreadId 29: Delay 4
1165-- The applicative instance of 'ZipAsync' type zips streams concurrently.
1166-- 'zipAsyncly' type combinator can be used to switch to parallel applicative
1172-- import qualified "Streamly.Prelude" as S
1173-- import Control.Concurrent
1174-- import System.IO (stdout, hSetBuffering, BufferMode(LineBuffering))
1176-- d n = delay n >> return n
1177-- s1 = 'serially' $ d 1 <> d 2
1178-- s2 = 'serially' $ d 3 <> d 4
1181-- hSetBuffering stdout LineBuffering
1182-- (S.'toList' . 'zipAsyncly' $ (,) \<$> s1 \<*> s2) >>= print
1185-- This takes 7 seconds to zip, which is max (1,3) + max (2,4) because 1 and 3
1186-- are produced concurrently, and 2 and 4 are produced concurrently:
1189-- ThreadId 32: Delay 1
1190-- ThreadId 32: Delay 2
1191-- ThreadId 33: Delay 3
1192-- ThreadId 33: Delay 4
1198-- When writing concurrent programs there are two distinct places where the
1199-- programmer can control the concurrency. First, when /composing/ a stream by
1200-- merging multiple streams we can choose an appropriate sum style operators to
1201-- combine them concurrently or serially. Second, when /processing/ a stream in
1202-- a monadic composition we can choose one of the monad composition types to
1203-- choose the desired type of concurrency.
1205-- In the following example the squares of @x@ and @y@ are computed
1206-- concurrently using the 'async' operation and the square roots of their
1207-- sum are computed serially because of the 'streamly' combinator. We can
1208-- choose different combinators for the monadic processing and the stream
1209-- generation, to control the concurrency. We can also use the 'asyncly'
1210-- combinator instead of explicitly folding with 'async'.
1214-- import qualified "Streamly.Prelude" as S
1215-- import Data.List (sum)
1219-- $ 'serially' -- Serial monadic processing (sqrt below)
1221-- x2 \<- 'forEachWith' 'async' [1..100] $ -- Concurrent @"for"@ loop
1222-- \\x -> return $ x * x -- body of the loop
1223-- y2 \<- 'forEachWith' 'async' [1..100] $
1224-- \\y -> return $ y * y
1225-- return $ sqrt (x2 + y2)
1229-- We can see how this directly maps to the imperative style
1230-- <https://en.wikipedia.org/wiki/OpenMP OpenMP> model, we use combinators
1231-- and operators instead of the ugly pragmas.
1233-- For more concurrent programming examples see,
1234-- "ListDir.hs", "MergeSort.hs" and "SearchQuery.hs" in the examples directory.
1238-- Reactive programming is nothing but concurrent streaming which is what
1239-- streamly is all about. With streamly we can generate streams of events,
1240-- merge streams that are generated concurrently and process events
1241-- concurrently. We can do all this without any knowledge about the specifics
1242-- of the implementation of concurrency. In the following example you will see
1243-- that the code is just regular Haskell code without much streamly APIs used
1244-- (active hyperlinks are the streamly APIs) and yet it is a reactive
1247-- This application has two independent and concurrent sources of event
1248-- streams, @acidRain@ and @userAction@. @acidRain@ continuously generates
1249-- events that deteriorate the health of the character in the game.
1250-- @userAction@ can be "potion" or "quit". When the user types "potion" the
1251-- health improves and the game continues.
1254-- {-\# LANGUAGE FlexibleContexts #-}
1257-- import Control.Concurrent (threadDelay)
1258-- import Control.Monad (when)
1259-- import Control.Monad.IO.Class (MonadIO(..))
1260-- import Control.Monad.State (MonadState, get, modify, runStateT)
1261-- import Data.Semigroup (cycle1)
1263-- data Event = Harm Int | Heal Int | Quit deriving (Show)
1265-- userAction :: MonadIO m => 'SerialT' m Event
1266-- userAction = cycle1 $ liftIO askUser
1269-- command <- getLine
1271-- "potion" -> return (Heal 10)
1272-- "quit" -> return Quit
1273-- _ -> putStrLn "What?" >> askUser
1275-- acidRain :: MonadIO m => 'SerialT' m Event
1276-- acidRain = cycle1 $ liftIO (threadDelay 1000000) >> return (Harm 1)
1278-- game :: ('MonadAsync' m, MonadState Int m) => 'SerialT' m ()
1280-- event \<- userAction \`parallel` acidRain
1282-- Harm n -> modify $ \\h -> h - n
1283-- Heal n -> modify $ \\h -> h + n
1284-- Quit -> fail "quit"
1287-- when (h <= 0) $ fail "You die!"
1288-- liftIO $ putStrLn $ "Health = " ++ show h
1291-- putStrLn "Your health is deteriorating due to acid rain,\\
1292-- \\ type \\"potion\\" or \\"quit\\""
1293-- _ <- runStateT ('runStream' game) 60
1297-- You can also find the source of this example in the examples directory as
1298-- "AcidRain.hs". It has been adapted from Gabriel's
1299-- <https://hackage.haskell.org/package/pipes-concurrency-2.0.8/docs/Pipes-Concurrent-Tutorial.html pipes-concurrency>
1301-- This is much simpler compared to the pipes version because of the builtin
1302-- concurrency in streamly. You can also find a SDL based reactive programming
1303-- example adapted from Yampa in "Streamly.Examples.CirclingSquare".
1307-- Streamly is highly optimized for performance, it is designed for serious
1308-- high performing, concurrent and scalable applications. We have created the
1309-- <https://hackage.haskell.org/package/streaming-benchmarks streaming-benchmarks>
1310-- package which is specifically and carefully designed to measure the
1311-- performance of Haskell streaming libraries fairly and squarely in the right
1312-- way. Streamly performs at par or even better than most streaming libraries
1313-- for serial operations even though it needs to deal with the concurrency
1318-- We can use @unfoldr@ and @uncons@ to convert one streaming type to another.
1320-- Interop with @vector@:
1324-- import qualified Streamly.Prelude as S
1325-- import qualified Data.Vector.Fusion.Stream.Monadic as V
1328-- -- streamly to vector
1329-- V.toList (V.unfoldrM S.uncons (S.fromFoldable [1..3])) >>= print
1331-- -- vector to streamly
1332-- S.toList (S.unfoldrM unconsV (V.fromList [1..3])) >>= print
1338-- then return Nothing
1341-- return $ Just (h, V.tail v)
1344-- Interop with @pipes@:
1348-- import qualified "Streamly.Prelude" as S
1349-- import qualified Pipes as P
1350-- import qualified Pipes.Prelude as P
1353-- -- streamly to pipe
1354-- P.toListM (P.unfoldr unconsS (S.'fromFoldable' [1..3])) >>= print
1356-- -- pipe to streamly
1357-- S.'toList' (S.'unfoldrM' unconsP (P.each [1..3])) >>= print
1360-- -- Adapt P.next to return a Maybe instead of Either
1361-- unconsP p = P.next p >>= either (\\_ -> return Nothing) (return . Just)
1363-- -- Adapt S.uncons to return an Either instead of Maybe
1364-- unconsS s = S.'uncons' s >>= maybe (return $ Left ()) (return . Right)
1367-- Interop with @streaming@:
1371-- import qualified "Streamly.Prelude" as S
1372-- import qualified Streaming as SG
1373-- import qualified Streaming.Prelude as SG
1376-- -- streamly to streaming
1377-- SG.toList (SG.unfoldr unconsS (S.'fromFoldable' [1..3])) >>= print
1379-- -- streaming to streamly
1380-- S.'toList' (S.unfoldrM SG.uncons (SG.each [1..3])) >>= print
1384-- -- Adapt S.uncons to return an Either instead of Maybe
1385-- unconsS s = S.'uncons' s >>= maybe (return $ Left ()) (return . Right)
1388-- Interop with @conduit@:
1392-- import qualified "Streamly.Prelude" as S
1393-- import qualified Data.Conduit as C
1394-- import qualified Data.Conduit.List as C
1395-- import qualified Data.Conduit.Combinators as C
1398-- -- streamly to conduit
1399-- C.runConduit (C.unfoldM S.'uncons' (S.'fromFoldable' [1..3]) C..| C.sinkList) >>= print
1401-- -- It seems there is no way out of a conduit as it does not provide an
1402-- -- uncons or a tail function.
1407-- List transformers and logic programming monads also provide a product style
1408-- composition similar to streamly, however streamly generalizes it with the
1409-- time dimension; allowing streams to be composed in an asynchronous and
1410-- concurrent fashion in many different ways. It also provides multiple
1411-- alternative ways of composing streams e.g. serial, interleaved or
1414-- This seemingly simple addition of asynchronicity and concurrency to product
1415-- style streaming composition unifies a number of disparate abstractions into
1416-- one powerful, concise and elegant abstraction. A wide variety of
1417-- programming problems can be solved elegantly with this abstraction. In
1418-- particular, it unifies three major programming domains namely
1419-- non-deterministic (logic) programming, concurrent programming and functional
1420-- reactive programming. In other words, you can do everything with this one
1421-- abstraction that you could do with the popular libraries listed under these
1422-- categories in the list below.
1425-- +-----------------+----------------+
1426-- | Non-determinism | <https://hackage.haskell.org/package/pipes pipes> |
1427-- | +----------------+
1428-- | | <https://hackage.haskell.org/package/list-t list-t> |
1429-- | +----------------+
1430-- | | <https://hackage.haskell.org/package/logict logict> |
1431-- +-----------------+----------------+
1432-- | Streaming | <https://hackage.haskell.org/package/vector vector> |
1433-- | +----------------+
1434-- | | <https://hackage.haskell.org/package/streaming streaming> |
1435-- | +----------------+
1436-- | | <https://hackage.haskell.org/package/pipes pipes> |
1437-- | +----------------+
1438-- | | <https://hackage.haskell.org/package/conduit conduit> |
1439-- +-----------------+----------------+
1440-- | Concurrency | <https://hackage.haskell.org/package/async async> |
1441-- | +----------------+
1442-- | | <https://hackage.haskell.org/package/transient transient> |
1443-- +-----------------+----------------+
1444-- | FRP | <https://hackage.haskell.org/package/Yampa Yampa> |
1445-- | +----------------+
1446-- | | <https://hackage.haskell.org/package/dunai dunai> |
1447-- | +----------------+
1448-- | | <https://hackage.haskell.org/package/reflex reflex> |
1449-- +-----------------+----------------+
1452-- Streamly is a list-transformer. It provides all the functionality provided
1453-- by any of the list transformer and logic programming packages listed above.
1454-- In addition, Streamly naturally integrates the concurrency dimension to the
1455-- basic list transformer functionality.
1457-- When it comes to streaming, in terms of the streaming API streamly is almost
1458-- identical to the vector package. Streamly, vector and streaming packages all
1459-- represent a stream as data and are therefore similar in the fundamental
1460-- approach to streaming. The fundamental difference is that streamly adds
1461-- concurrency support and the monad instance provides concurrent looping.
1462-- Other streaming libraries like pipes, conduit and machines represent and
1463-- compose stream processors rather than the stream data and therefore fall in
1464-- another class of streaming libraries and have comparatively more complicated
1467-- When it comes to concurrency, streamly can do everything that the @async@
1468-- package can do and more. async provides applicative concurrency whereas
1469-- streamly provides both applicative and monadic concurrency. The
1470-- 'ZipAsync' type behaves like the applicative instance of async. In
1471-- comparison to transient streamly has a first class streaming interface and
1472-- is a monad transformer that can be used universally in any Haskell monad
1473-- transformer stack. Streamly was in fact originally inspired by the
1474-- concurrency implementation in @transient@ though it has no resemblence with
1475-- that and takes a lazy pull approach versus transient's strict push approach.
1477-- The non-determinism, concurrency and streaming combination make streamly a
1478-- strong FRP capable library as well. FRP is fundamentally stream of events
1479-- that can be processed concurrently. The example in this tutorial as well as
1480-- the "Streamly.Examples.CirclingSquare" example from Yampa demonstrate the
1481-- basic FRP capability of streamly. In core concepts streamly is strikingly
1482-- similar to @dunai@. dunai was designed from a FRP perspective and streamly
1483-- was originally designed from a concurrency perspective. However, both have
1484-- similarity at the core.
1488-- * Read the documentation of "Streamly" module
1489-- * Read the documentation of "Streamly.Prelude" module
1490-- * See the examples in the "examples" directory of the package
1491-- * 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