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 -- * Generating Streams
43 -- * Eliminating Streams
46 -- * Transforming Streams
54 -- *** Serial Depth First Composition ('Stream')
57 -- *** Serial Breadth First Composition ('Costream')
60 -- *** Concurrent Depth First Composition ('ParAhead')
63 -- *** Concurrent Breadth First Composition ('CoParAhead')
66 -- *** Custom composition
78 -- *** Serial Depth First Nesting ('Stream')
81 -- *** Serial Breadth First Nesting ('Costream')
82 -- $interleavedNesting
84 -- *** Concurrent Depth First Nesting ('ParAhead')
87 -- *** Concurrent Breadth First Nesting ('CoparAhead')
88 -- $fairlyConcurrentNesting
105 -- ** Parallel Zipping
108 -- * Summary of Compositions
109 -- $compositionSummary
111 -- * Monad transformers
112 -- $monadtransformers
114 -- * Concurrent Programming
117 -- * Reactive Programming
123 -- * Interoperation with Streaming Libraries
126 -- * Comparison with Existing Packages
129 -- * Where to go next?
135import Streamly.Prelude
137import Control.Applicative
139import Control.Monad.IO.Class (MonadIO(..))
140import Control.Monad.Trans.Class (MonadTrans (lift))
144-- The way a list represents a sequence of pure values, a stream represents a
145-- sequence of monadic actions. The monadic stream API offered by Streamly is
146-- very close to the Haskell "Prelude" pure lists' API, it can be considered as a
147-- natural extension of lists to monadic actions. Streamly streams provide
148-- concurrent composition and merging of streams. It can be considered as a
149-- concurrent list transformer. In contrast to the "Prelude" lists, merging or
150-- appending streams of arbitrary length is scalable and inexpensive.
152-- The basic stream type is 'Stream', it represents a sequence of IO actions,
153-- and is a 'Monad'. The type 'StreamT' is a monad transformer that can
154-- represent a sequence of actions in an arbitrary monad. The type 'Stream' is
155-- in fact a synonym for @StreamT IO@. There are a few more types similar to
156-- 'StreamT' that all represent streams and differ only in the 'Semigroup',
157-- 'Applicative' and 'Monad' compositions of the streams. 'Stream' and
158-- 'Costream' types compose serially whereas 'ParAhead' and 'CoparAhead' types
159-- compose concurrently. All these types can be freely inter-converted using
160-- type combinators without any cost. You can freely switch to any type of
161-- composition at any point in the program. When no type annotation or
162-- explicit stream type combinators are used, the default stream type is
163-- inferred as 'Stream'.
165-- The 'Stream' monad is almost a drop in replacement for the 'IO' monad, IO
166-- monad is a special case of the 'Stream' monad; IO monad represents a single
167-- IO action whereas the 'Stream' monad represents a sequence of IO actions.
168-- The only change you need to make to go from 'IO' to 'Stream' is to use
169-- 'runStream' to run the monad and to prefix the IO actions with 'once'. You
170-- can also use 'liftIO' instead of 'once'. In fact, if you use liftIO you can
171-- switch from 'Stream' to IO monad by simply removing the 'runStream'
172-- function; no other changes are needed unless you have used some stream
173-- specific composition or combinators.
175-- Similarly, the 'Stream' type is almost a drop in replacement for pure lists,
176-- pure lists are a special case of monadic streams. If you use 'nil' in place
177-- of '[]' and '|:' in place ':' you can replace a list with a 'Stream'. The
178-- only difference is that the elements must be monadic type and to operate on
179-- the streams we must use the corresponding functions from "Streamly.Prelude"
180-- instead of using the base "Prelude".
184-- To represent streams in an arbitrary monad use the more general monad
185-- transformer types for example the monad transformer type corresponding to
186-- the 'Stream' type is 'StreamT'. @StreamT m a@ represents a stream of values
187-- of type 'a' in some underlying monad 'm'. For example, @StreamT IO Int@ is a
188-- stream of 'Int' in 'IO' monad. In fact, the type 'Stream' is a synonym for
191-- Similarly we have monad transformer types for other stream types as well viz.
192-- 'CostreamT', 'ParAheadT' and 'CoparAheadT'.
194-- To lift a value from an underlying monad in a monad transformer stack into a
195-- singleton stream use 'lift' and to lift from an IO action use 'liftIO'.
198-- > 'runStream' $ liftIO $ putStrLn "Hello world!"
200-- > 'runStream' $ lift $ putStrLn "Hello world!"
207-- We will assume the following imports in this tutorial. Go ahead, fire up a
208-- GHCi session and import these lines to start playing.
211-- > import "Streamly"
212-- > import "Streamly.Prelude" (|:)
213-- > import qualified "Streamly.Prelude" as S
216-- 'nil' represents an empty stream and 'consM' or its operator form '|:' adds
217-- a monadic action at the head of the stream.
220-- > S.'toList' S.'nil'
222-- > S.'toList' $ 'getLine' |: 'getLine' |: S.'nil'
228-- To create a singleton stream from a pure value use 'pure' and to create a
229-- singleton stream from a monadic action use 'once'.
232-- > S.'toList' $ 'pure' 1
234-- > S.'toList' $ S.'once' 'getLine'
239-- To create a stream from pure values in a 'Foldable' container use
240-- 'fromFoldable' which is equivalent to a fold using 'cons' and 'nil':
243-- > S.'toList' $ S.'fromFoldable' [1..3]
245-- > S.'toList' $ 'Prelude.foldr' S.'cons' S.'nil' [1..3]
249-- To create a stream from monadic actions in a 'Foldable' container just use a
250-- right fold using 'consM' and 'nil':
253-- > 'runStream' $ 'Prelude.foldr' ('|:') S.'nil' ['putStr' "Hello ", 'putStrLn' "world!"]
257-- For more ways to construct a stream see the module "Streamly.Prelude".
261-- We have already seen 'runStream' and 'toList' to eliminate a stream in the
262-- examples above. 'runStream' runs a stream discarding the results i.e. only
263-- for effects. 'toList' runs the stream and collects the results in a list.
265-- For other ways to eliminate a stream see the @Folding@ section in
266-- "Streamly.Prelude" module.
270-- Transformation over a stream is the equivalent of a @for@ loop construct in
271-- imperative paradigm. We iterate over every element in the stream and perform
272-- certain transformations for each element. Transformations may involve
273-- mapping functions over the elements, filtering elements from the stream or
274-- folding all the elements in the stream into a single value. Streamly streams
275-- are exactly like lists and you can perform all the transformations in the
276-- same way as you would on lists.
278-- Here is a simple console echo program that just echoes every input line,
282-- > 'runStream' $ S.'repeatM' getLine & S.'mapM' putStrLn
285-- The following code snippet reads lines from standard input, filters blank
286-- lines, drops the first non-blank line, takes the next two, up cases them,
287-- numbers them and prints them:
291-- import qualified "Streamly.Prelude" as S
292-- import Data.Char (toUpper)
293-- import Data.Function ((&))
295-- main = 'runStream' $
296-- S.'repeatM' getLine
297-- & S.'filter' (not . null)
300-- & fmap (map toUpper)
301-- & S.'zipWith' (\\n s -> show n ++ " " ++ s) (S.'fromFoldable' [1..])
302-- & S.'mapM' putStrLn
307-- We can combine two streams into a single stream using semigroup composition
308-- operation '<>'. Streams can be combined in many different ways as described
309-- in the following sections, the '<>' operation behaves differently depending
310-- on the stream type in effect. Streamly streams can be of many
311-- different types i.e. 'Stream', 'Costream', 'ParAhead', 'CoparAhead',
312-- 'ZipStream', and 'ZipParallel'. The first four are monads whereas the last
313-- two are applicatives. These types can be freely converted from one to
314-- another to acheive the desired composition style. To force a particular
315-- type of composition we coerce the stream type using the corresponding type
316-- adapting combinator from 'asStream', 'asCostream', 'asParAhead',
317-- 'asCoparAhead', 'asZipStream' or 'asZipParallel'. The default stream type is
318-- 'Stream' unless you change it by using one of the combinators.
320-- To illustrate the concurrent vs serial composition aspects, we will use the
321-- following @delay@ function to introduce a delay specified in seconds.
325-- import "Streamly.Prelude" (nil)
326-- import qualified "Streamly.Prelude" as S
327-- import Control.Concurrent
329-- delay n = S.'once' $ do
330-- threadDelay (n * 1000000)
332-- putStrLn (show tid ++ ": Delay " ++ show n)
337-- The 'Semigroup' operation '<>' of the 'Stream' type combines the two streams
338-- in a /serial depth first/ manner. We use the 'asStream' type combinator to
339-- effect 'Stream' style of composition. We can also use an explicit 'Stream'
340-- type annotation for the stream to acheive the same effect. However, since
341-- 'Stream' is the default type unless explicitly specified by using a
342-- combinator, we can omit using an explicit combinator or type annotation for
343-- this style of composition.
345-- When two streams with multiple elements are combined in this manner, the
346-- monadic actions in the two streams are performed sequentially i.e. first all
347-- actions in the first stream are performed sequentially and then all actions
348-- in the second stream are performed sequentially. We call it
349-- /serial depth first/ as the full depth of one stream is fully traversed
350-- before we move to the next. The following example prints the sequence 1, 2,
354-- main = 'runStream' $ (print 1 |: print 2 |: nil) <> (print 3 |: print 4 |: nil)
363-- All actions in both the streams are performed serially in the same thread.
364-- In the following example we can see that all actions are performed in the
365-- same thread and take a combined total of 6 seconds:
368-- main = 'runStream' $ delay 3 <> delay 2 <> delay 1
371-- ThreadId 36: Delay 3
372-- ThreadId 36: Delay 2
373-- ThreadId 36: Delay 1
376-- The polymorphic version of the 'Stream' binary operation '<>' is called
377-- 'splice'. We can use 'splice' to join streams in a sequential manner
378-- irrespective of the type of stream:
381-- main = 'runStream' $ (print 1 |: print 2 |: nil) \`splice` (print 3 |: print 4 |: nil)
386-- The 'Semigroup' operation '<>' of the 'Costream' type combines the two
387-- streams in a /serial breadth first/ manner. We use the 'asCostream' type
388-- combinator to effect 'Costream' style of composition. We can also use the
389-- 'Costream' type annotation for the stream to acheive the same effect.
391-- When two streams with multiple elements are combined in this manner, we
392-- traverse all the streams in a breadth first manner i.e. one action from each
393-- stream is peformed and yielded to the resulting stream before we come back
394-- to the first stream again and so on.
395-- The following example prints the sequence 1, 3, 2, 4
398-- main = 'runStream' . 'asCostream' $ (print 1 |: print 2 |: nil) <> (print 3 |: print 4 |: nil)
407-- Even though the monadic actions of the two streams are performed in an
408-- interleaved manner they are all performed serially in the same thread. In
409-- the following example we can see that all actions are performed in the same
410-- thread and take a combined total of 6 seconds:
413-- main = 'runStream' . 'asCostream' $ delay 3 <> delay 2 <> delay 1
416-- ThreadId 36: Delay 3
417-- ThreadId 36: Delay 2
418-- ThreadId 36: Delay 1
421-- The polymorphic version of the 'Costream' binary operation '<>' is called
422-- 'cosplice'. We can use 'cosplice' to join streams in an interleaved manner
423-- irrespective of the type, notice that we have not used the 'asCostream'
424-- combinator in the following example:
427-- main = 'runStream' $ (print 1 |: print 2 |: nil) \`cosplice` (print 3 |: print 4 |: nil)
436-- Note that this composition cannot be used to fold infinite number of streams
437-- since it requires preserving the state until a stream is finished.
441-- The 'Semigroup' operation '<>' of the 'ParAhead' type combines the two
442-- streams in a depth first manner with parallel look ahead. We use the
443-- 'asParAhead' type combinator to effect 'ParAhead' style of composition. We
444-- can also use the 'ParAhead' type annotation for the stream type to acheive
447-- When two streams with multiple elements are combined in this manner, the
448-- streams are traversed in depth first manner just like 'Stream', however it
449-- can execute the next stream concurrently and return the results from it
450-- as they arrive i.e. the results from the next stream may be yielded even
451-- before the results from the first stream. Concurrent execution of the next
452-- stream(s) is performed if the first stream blocks or if it cannot produce
453-- output at the rate that is enough to meet the consumer demand. Multiple
454-- streams can be executed concurrently to meet the demand.
455-- In the following example the first stream does not block,
456-- therefore the first stream is completely exhausted before the second.
459-- main = 'runStream' . 'asParAhead' $ (print 1 |: print 2 |: nil) <> (print 3 |: print 4 |: nil)
468-- If the first stream blocks, we can yield from the second. In the example
469-- below each yield in the stream has a constant delay of 1 second therefore 1
470-- and 3 would be yielded first and then 2 and 4 would be yielded.
473-- main = 'runStream' . 'asParAhead' $ (p 1 |: p 2 |: nil) <> (p 3 |: p 4 |: nil)
474-- where p n = threadDelay 1000000 >> print n
483-- In the following example we can see that new threads are started when a
484-- computation blocks. Notice that the output from the stream with the
485-- shortest delay is printed first:
488-- main = 'runStream' . 'asParAhead' $ delay 3 '<>' delay 2 '<>' delay 1
491-- ThreadId 42: Delay 1
492-- ThreadId 41: Delay 2
493-- ThreadId 40: Delay 3
496-- When we have a tree of computations composed using this style, the tree is
497-- traversed in DFS style just like the serial style, the only difference is
498-- that here we can move on to executing the next stream if a stream blocks.
499-- However, we will not start new threads if we have sufficient output to
500-- saturate the consumer. This is why we call it left-biased demand driven or
501-- adaptive concurrency style, the concurrency tends to stay on the left side
502-- of the composition as long as possible. More threads are started based on
503-- the pull rate of the consumer. The following example prints an output every
504-- second as all of the actions are concurrent.
507-- main = 'runStream' . 'asParAhead' $ (delay 1 <> delay 2) <> (delay 3 <> delay 4)
516-- All the computations may even run in a single thread when more threads are
517-- not needed. As you can see, in the following example the computations are
518-- run in a single thread one after another, because none of them blocks.
519-- However, if the thread consuming the stream were faster than the producer
520-- then it would have started parallel threads for each computation to keep up
521-- even if none of them blocks:
524-- main = 'runStream' . 'asParAhead' $ traced (sqrt 9) '<>' traced (sqrt 16) '<>' traced (sqrt 25)
525-- where traced m = S.'once' (myThreadId >>= print) >> return m
533-- Note that the order of printing in the above examples may change due to
534-- variations in scheduling latencies for concurrent threads.
536-- The polymorphic version of the 'ParAhead' binary operation '<>' is called
537-- 'parAhead'. We can use 'parAhead' to join streams in a left biased
538-- adaptively concurrent manner irrespective of the type, notice that we have
539-- not used the 'asParAhead' combinator in the following example:
542-- main = 'runStream' $ delay 3 \`parAhead` delay 2 \`parAhead` delay 1
545-- ThreadId 42: Delay 1
546-- ThreadId 41: Delay 2
547-- ThreadId 40: Delay 3
550-- Since the concurrency provided by this operator is demand driven it cannot
551-- be used when the composed computations start timers that are relative to
552-- each other because all computations may not be started at the same time and
553-- therefore timers in all of them may not start at the same time. When
554-- relative timing among all computations is important or when we need to start
555-- all computations at once for any reason 'Parallel' style must be used
558-- 'ParAhead' style should be preferred over 'CoparAhead' unless you really
559-- need 'CoparAhead'. It utilizes the resources optimally. It should be used when
560-- we know that the computations can run in parallel but we do not care if they
561-- actually run in parallel or not, that decision can be left to the scheduler
562-- based on demand. Also, note that this operator can be used to fold infinite
563-- number of streams in contrast to the 'CoparAhead' style, because it does not
564-- require us to run all of them at the same time in a fair manner.
568-- The 'Semigroup' operation '<>' of the 'Parallel' type combines the two
569-- streams in a fairly concurrent manner with round robin scheduling. We use
570-- the 'parallel' type combinator to effect 'Parallel' style of composition. We
571-- can also use the 'Parallel' type annotation for the stream type to acheive
574-- When two streams with multiple elements are combined in this manner, the
575-- monadic actions in both the streams are performed concurrently with a fair
576-- round robin scheduling. The outputs are yielded in the order in which the
577-- actions complete. This can be thought of as the concurrent analogue of the
578-- 'Costream' style serial composition.
580-- The following example sends a query to all the three search engines in
581-- parallel and prints the name of the search engines in the order in which the
586-- import qualified Streamly.Prelude as S
587-- import Network.HTTP.Simple
589-- main = 'runStream' . 'asParallel' $ google \<> bing \<> duckduckgo
591-- google = get "https://www.google.com/search?q=haskell"
592-- bing = get "https://www.bing.com/search?q=haskell"
593-- duckduckgo = get "https://www.duckduckgo.com/?q=haskell"
594-- get s = S.'once' (httpNoBody (parseRequest_ s) >> putStrLn (show s))
597-- In the following example we can see that the co-ahead parallel composition
598-- yields outputs in the same order as the 'Costream' composition, though this
599-- is not always guaranteed because of thread scheduling variances.
602-- main = 'runStream' . 'asCoparAhead' $ (print 1 |: print 2 |: nil) <> (print 3 |: print 4 |: nil)
611-- The polymorphic version of the 'CoparAhead' binary operation '<>' is called
612-- 'coparAhead'. We can use 'coparAhead' to join streams in a fairly
613-- concurrent manner irrespective of the type, notice that we have
614-- not used the 'asCoparAhead' combinator in the following example:
617-- main = 'runStream' $ delay 3 \`coparAhead` delay 2 \`coparAhead` delay 1
620-- ThreadId 42: Delay 1
621-- ThreadId 41: Delay 2
622-- ThreadId 40: Delay 3
625-- Note that this style of composition cannot be used to combine infinite
626-- number of streams, as it will lead to an infinite sized scheduling queue.
631-- The 'async' API can be used to create references to asynchronously running
632-- stream computations. We can then use 'uncons' to explore the streams
633-- arbitrarily and then recompose individual elements to create a new stream.
634-- This way we can dynamically decide which stream to explore at any given
635-- time. Take an example of a merge sort of two sorted streams. We need to
636-- keep consuming items from the stream which has the lowest item in the sort
637-- order. This can be achieved using async references to streams. See
638-- "MergeSort.hs" in the examples directory.
642-- We can use 'Monoid' instances to fold a container of streams in the desired
643-- style using 'fold' or 'foldMap'. We have also provided some fold utilities
644-- to fold streams using the polymorphic combine operations:
646-- * 'foldWith' is like 'fold', it folds a 'Foldable' container of streams
647-- using the given composition operator.
648-- * 'foldMapWith' is like 'foldMap', it folds like @foldWith@ but also maps a
649-- function before folding.
650-- * 'forEachWith' is like @foldMapwith@ but the container argument comes before
651-- the function argument.
653-- All of the following are equivalent and start ten concurrent tasks each with
654-- a delay from 1 to 10 seconds, resulting in the printing of each number every
659-- import qualified "Streamly.Prelude" as S
660-- import Control.Concurrent
663-- 'runStream' $ 'asParAhead' $ foldMap delay [1..10]
664-- 'runStream' $ 'foldWith' 'parAhead' (map delay [1..10])
665-- 'runStream' $ 'foldMapWith' 'parAhead' delay [1..10]
666-- 'runStream' $ 'forEachWith' 'parAhead' [1..10] delay
667-- where delay n = S.'once' $ threadDelay (n * 1000000) >> print n
672-- Till now we discussed ways to apply transformations on a stream or to merge
673-- streams together to create another stream. We mentioned earlier that
674-- transforming a stream is similar to a @for@ loop in the imperative paradigm.
675-- We will now discuss the concept of a nested composition of streams which is
676-- analogous to nested @for@ loops in the imperative paradigm. Functional
677-- programmers call this style of composition a list transformer or @ListT@.
678-- Logic programmers call it a logic monad or non-deterministic composition,
679-- but for ordinary imperative minded people like me it is easier to think in
680-- terms of good old nested @for@ loops.
684-- In functional programmer's parlance the 'Monad' instances of different
685-- 'IsStream' types implement non-determinism, exploring all possible
686-- combination of choices from both the streams. From an imperative
687-- programmer's point of view it behaves like nested loops i.e. for each
688-- element in the first stream and for each element in the second stream
689-- execute the body of the loop.
691-- The 'Monad' instances of 'Stream', 'Costream', 'ParAhead' and 'CoparAhead'
692-- stream types support different flavors of nested looping. In other words,
693-- they are all variants of list transformer. The nesting behavior of these
694-- types exactly correspond to the way they merge streams as we discussed in
695-- the previous section.
700-- The 'Monad' composition of 'Stream' type behaves like a standard list
701-- transformer. This is the default when we do not use an explicit type
702-- combinator. However, the 'streamly' type combinator can be used to switch to
703-- this style of composition. We will see how this style of composition works
704-- in the following examples.
706-- Let's start with an example with a simple @for@ loop without any nesting.
707-- For simplicity of illustration we are using streams of pure values in all
708-- the examples. However, the streams could also be made of monadic actions
713-- import qualified "Streamly.Prelude" as S
715-- main = 'runStream' $ do
716-- x <- S.'fromFoldable' [3,2,1]
720-- ThreadId 30: Delay 3
721-- ThreadId 30: Delay 2
722-- ThreadId 30: Delay 1
725-- As you can see, the code after the @fromFoldable@ statement is run three
726-- times, once for each value of @x@ drawn from the stream. All the three
727-- iterations are serial and run in the same thread one after another. In
728-- imperative terms this is equivalent to a @for@ loop with three iterations.
730-- A console echo loop copying standard input to standard output can simply be
735-- import qualified "Streamly.Prelude" as S
737-- main = 'runStream' $ forever $ S.once getLine >>= S.once . putStrLn
740-- When multiple streams are composed using this style they nest in a DFS
741-- manner i.e. nested iterations of a loop are executed before we proceed to
742-- the next iteration of the parent loop. This behaves just like nested @for@
743-- loops in imperative programming.
747-- import qualified "Streamly.Prelude" as S
749-- main = 'runStream' $ do
750-- x <- S.'fromFoldable' [1,2]
751-- y <- S.'fromFoldable' [3,4]
752-- S.'once' $ putStrLn $ show (x, y)
761-- Notice that this is analogous to merging streams of type 'Stream' or merging
762-- streams using 'splice'.
766-- The 'Monad' composition of 'ParAhead' type can perform the iterations of a
767-- loop concurrently. Concurrency is demand driven i.e. more concurrent
768-- iterations are started only if the previous iterations are not able to
769-- produce enough output for the consumer of the output stream. This works
770-- exactly the same way as the merging of two streams 'asParAhead' works.
771-- This is the concurrent analogue of 'Stream' style monadic composition.
773-- The 'asParAhead' type combinator can be used to switch to this
774-- style of composition. Alternatively, a type annotation can be used to
775-- specify the type of the stream as 'ParAhead'.
779-- import "Streamly.Prelude"
781-- main = 'runStream' . 'asParAhead' $ do
782-- x <- 'fromFoldable' [3,2,1]
786-- ThreadId 40: Delay 1
787-- ThreadId 39: Delay 2
788-- ThreadId 38: Delay 3
791-- As you can see the code after the @fromFoldable@ statement is run three
792-- times, once for each value of @x@. All the three iterations are concurrent
793-- and run in different threads. The iteration with least delay finishes first.
794-- When compared to imperative programming, this can be viewed as a @for@ loop
795-- with three concurrent iterations.
797-- Concurrency is demand driven just as in the case of 'parAhead' merging.
798-- When multiple streams are composed using this style, the iterations are
799-- triggered in a DFS manner just like 'Stream' i.e. nested iterations are
800-- executed before we proceed to the next iteration at higher level. However,
801-- unlike 'Stream' more than one iterations may be started concurrently based
802-- on the demand from the consumer.
806-- import qualified "Streamly.Prelude" as S
808-- main = 'runStream' . 'asParAhead' $ do
809-- x <- S.'fromFoldable' [1,2]
810-- y <- S.'fromFoldable' [3,4]
811-- S.'once' $ putStrLn $ show (x, y)
820-- $interleavedNesting
822-- The 'Monad' composition of 'Costream' type interleaves the iterations of
823-- outer and inner loops in a nested loop composition. This works exactly the
824-- same way as the merging of two streams in 'asCostream' fashion works. The
825-- 'asCostream' type combinator can be used to switch to this style of
826-- composition. Alternatively, a type annotation can be used to specify the
827-- type of the stream as 'Costream'.
831-- import qualified "Streamly.Prelude" as S
833-- main = 'runStream' . 'asCostream' $ do
834-- x <- S.'fromFoldable' [1,2]
835-- y <- S.'fromFoldable' [3,4]
836-- S.once $ putStrLn $ show (x, y)
846-- $fairlyConcurrentNesting
848-- The 'Monad' composition of 'Parallel' type starts all the iterations of a
849-- loop concurrently instead of demand driven as in the case of 'ParAhead'.
850-- This works exactly the same way as the merging streams 'parallely' works.
851-- The 'parallely' type combinator can be used to switch to this style of
852-- composition. Alternatively, a type annotation can be used to specify the
853-- type of the stream as 'Parallel'.
857-- import qualified "Streamly.Prelude" as S
859-- main = 'runStream' . 'parallely' $ do
860-- x <- S.'fromFoldable' [3,2,1]
864-- ThreadId 40: Delay 1
865-- ThreadId 39: Delay 2
866-- ThreadId 38: Delay 3
871-- The streamly code is usually written in a way that is agnostic of the
872-- specific monadic composition type. We use a polymorphic type with a
873-- 'IsStream' type class constraint. When running the stream we can choose the
874-- specific mode of composition. For example take a look at the following code.
878-- import qualified "Streamly.Prelude" as S
880-- composed :: 'IsStream' t => t m a
885-- S.'once' $ putStrLn $ show (sz, cl, sh)
889-- sizes = S.'fromFoldable' [1, 2, 3]
890-- colors = S.'fromFoldable' ["red", "green", "blue"]
891-- shapes = S.'fromFoldable' ["triangle", "square", "circle"]
894-- Now we can interpret this in whatever way we want:
897-- main = 'runStream' . 'asStream' $ composed
898-- main = 'runStream' . 'asCostream' $ composed
899-- main = 'runStream' . 'asParAhead' $ composed
900-- main = 'runStream' . 'asCoparAhead' $ composed
903-- As an exercise try to figure out the output of this code for each mode of
908-- 'fmap' transforms a stream by mapping a function on all elements of the
909-- stream. 'fmap' behaves in the same way for all stream types, it is always
914-- import qualified "Streamly.Prelude" as S
916-- main = (S.'toList' $ fmap show $ S.'fromFoldable' [1..10]) >>= print
919-- Also see the 'mapM' and 'sequence' functions for mapping actions, in the
920-- "Streamly.Prelude" module.
924-- Applicative is precisely the same as the 'ap' operation of 'Monad'. For
925-- zipping applicatives separate types 'ZipStream' and 'ZipParallel' are
928-- The following example uses the 'Stream' applicative, it runs all iterations
929-- serially and takes a total 17 seconds (1 + 3 + 4 + 2 + 3 + 4):
933-- import qualified "Streamly.Prelude" as S
934-- import Control.Concurrent
938-- d n = delay n >> return n
940-- main = (S.'toList' . 'asStream' $ (,) \<$> s1 \<*> s2) >>= print
943-- ThreadId 36: Delay 1
944-- ThreadId 36: Delay 3
945-- ThreadId 36: Delay 4
946-- ThreadId 36: Delay 2
947-- ThreadId 36: Delay 3
948-- ThreadId 36: Delay 4
949-- [(1,3),(1,4),(2,3),(2,4)]
952-- Similalrly 'Costream' applicative runs the iterations in an interleaved
953-- order but since it is serial it takes a total of 17 seconds:
956-- main = (S.'toList' . 'asCostream' $ (,) \<$> s1 \<*> s2) >>= print
959-- ThreadId 36: Delay 1
960-- ThreadId 36: Delay 3
961-- ThreadId 36: Delay 2
962-- ThreadId 36: Delay 3
963-- ThreadId 36: Delay 4
964-- ThreadId 36: Delay 4
965-- [(1,3),(2,3),(1,4),(2,4)]
968-- 'ParAhead' can run the iterations concurrently and therefore takes a total
969-- of 10 seconds (1 + 2 + 3 + 4):
972-- main = (S.'toList' . 'asParAhead' $ (,) \<$> s1 \<*> s2) >>= print
975-- ThreadId 34: Delay 1
976-- ThreadId 36: Delay 2
977-- ThreadId 35: Delay 3
978-- ThreadId 36: Delay 3
979-- ThreadId 35: Delay 4
980-- ThreadId 36: Delay 4
981-- [(1,3),(2,3),(1,4),(2,4)]
984-- Similalrly 'CoparAhead' as well can run the iterations concurrently and
985-- therefore takes a total of 10 seconds (1 + 2 + 3 + 4):
988-- main = (S.'toList' . 'asCoparAhead' $ (,) \<$> s1 \<*> s2) >>= print
991-- ThreadId 34: Delay 1
992-- ThreadId 36: Delay 2
993-- ThreadId 35: Delay 3
994-- ThreadId 36: Delay 3
995-- ThreadId 35: Delay 4
996-- ThreadId 36: Delay 4
997-- [(1,3),(2,3),(1,4),(2,4)]
1000-- $compositionSummary
1002-- The following table summarizes the types for monadic and sum style
1006-- +-----+--------------+--------------+
1007-- | | Serial | Concurrent |
1008-- +=====+==============+==============+
1009-- | DFS | 'Stream' | 'ParAhead' |
1010-- +-----+--------------+--------------+
1011-- | BFS | 'Costream' | 'CoparAhead' |
1012-- +-----+--------------+--------------+
1017-- Zipping is a special transformation where the corresponding elements of two
1018-- streams are combined together using a zip function producing a new stream of
1019-- outputs. Two different types are provided for serial and concurrent zipping.
1020-- These types provide an applicative instance that can be used to lift
1021-- functions to zip the argument streams.
1022-- Also see the zipping functions in the "Streamly.Prelude" module.
1026-- The applicative instance of 'ZipStream' type zips streams serially.
1027-- 'asZipStream' type combinator can be used to switch to serial applicative
1032-- import qualified "Streamly.Prelude" as S
1033-- import Control.Concurrent
1035-- d n = delay n >> return n
1036-- s1 = 'streamly' $ d 1 <> d 2
1037-- s2 = 'streamly' $ d 3 <> d 4
1039-- main = (S.'toList' . 'asZipStream' $ (,) \<$> s1 \<*> s2) >>= print
1042-- This takes total 10 seconds to zip, which is (1 + 2 + 3 + 4) since
1043-- everything runs serially:
1046-- ThreadId 29: Delay 1
1047-- ThreadId 29: Delay 3
1048-- ThreadId 29: Delay 2
1049-- ThreadId 29: Delay 4
1055-- The applicative instance of 'ZipParallel' type zips streams concurrently.
1056-- 'asZipParallel' type combinator can be used to switch to parallel applicative
1062-- import qualified "Streamly.Prelude" as S
1063-- import Control.Concurrent
1064-- import System.IO (stdout, hSetBuffering, BufferMode(LineBuffering))
1066-- d n = delay n >> return n
1067-- s1 = 'streamly' $ d 1 <> d 2
1068-- s2 = 'streamly' $ d 3 <> d 4
1071-- hSetBuffering stdout LineBuffering
1072-- (S.'toList' . 'asZipParallel' $ (,) \<$> s1 \<*> s2) >>= print
1075-- This takes 7 seconds to zip, which is max (1,3) + max (2,4) because 1 and 3
1076-- are produced concurrently, and 2 and 4 are produced concurrently:
1079-- ThreadId 32: Delay 1
1080-- ThreadId 32: Delay 2
1081-- ThreadId 33: Delay 3
1082-- ThreadId 33: Delay 4
1088-- When writing concurrent programs there are two distinct places where the
1089-- programmer can control the concurrency. First, when /composing/ a stream by
1090-- merging multiple streams we can choose an appropriate sum style operators to
1091-- combine them concurrently or serially. Second, when /processing/ a stream in
1092-- a monadic composition we can choose one of the monad composition types to
1093-- choose the desired type of concurrency.
1095-- In the following example the squares of @x@ and @y@ are computed
1096-- concurrently using the 'parAhead' operation and the square roots of their
1097-- sum are computed serially because of the 'streamly' combinator. We can
1098-- choose different combinators for the monadic processing and the stream
1099-- generation, to control the concurrency. We can also use the 'asParAhead'
1100-- combinator instead of explicitly folding with 'parAhead'.
1104-- import qualified "Streamly.Prelude" as S
1105-- import Data.List (sum)
1109-- $ 'asStream' -- Serial monadic processing (sqrt below)
1111-- x2 \<- 'forEachWith' 'parAhead' [1..100] $ -- Concurrent @"for"@ loop
1112-- \\x -> return $ x * x -- body of the loop
1113-- y2 \<- 'forEachWith' 'parAhead' [1..100] $
1114-- \\y -> return $ y * y
1115-- return $ sqrt (x2 + y2)
1119-- You can see how this directly maps to the imperative style
1120-- <https://en.wikipedia.org/wiki/OpenMP OpenMP> model, we use combinators
1121-- and operators instead of the ugly pragmas.
1123-- For more concurrent programming examples see,
1124-- "ListDir.hs", "MergeSort.hs" and "SearchQuery.hs" in the examples directory.
1128-- Reactive programming is nothing but concurrent streaming which is what
1129-- streamly is all about. With streamly we can generate streams of events,
1130-- merge streams that are generated concurrently and process events
1131-- concurrently. We can do all this without any knowledge about the specifics
1132-- of the implementation of concurrency. In the following example you will see
1133-- that the code is just regular Haskell code without much streamly APIs used
1134-- (active hyperlinks are the streamly APIs) and yet it is a reactive
1137-- This application has two independent and concurrent sources of event
1138-- streams, @acidRain@ and @userAction@. @acidRain@ continuously generates
1139-- events that deteriorate the health of the character in the game.
1140-- @userAction@ can be "potion" or "quit". When the user types "potion" the
1141-- health improves and the game continues.
1144-- {-\# LANGUAGE FlexibleContexts #-}
1147-- import Control.Concurrent (threadDelay)
1148-- import Control.Monad (when)
1149-- import Control.Monad.State (MonadState, get, modify, runStateT)
1150-- import Data.Semigroup (cycle1)
1152-- data Event = Harm Int | Heal Int | Quit deriving (Show)
1154-- userAction :: MonadIO m => 'StreamT' m Event
1155-- userAction = cycle1 $ liftIO askUser
1158-- command <- getLine
1160-- "potion" -> return (Heal 10)
1161-- "quit" -> return Quit
1162-- _ -> putStrLn "What?" >> askUser
1164-- acidRain :: MonadIO m => 'StreamT' m Event
1165-- acidRain = cycle1 $ liftIO (threadDelay 1000000) >> return (Harm 1)
1167-- game :: ('MonadParallel' m, MonadState Int m) => 'StreamT' m ()
1169-- event \<- userAction \`parallel` acidRain
1171-- Harm n -> modify $ \\h -> h - n
1172-- Heal n -> modify $ \\h -> h + n
1173-- Quit -> fail "quit"
1176-- when (h <= 0) $ fail "You die!"
1177-- liftIO $ putStrLn $ "Health = " ++ show h
1180-- putStrLn "Your health is deteriorating due to acid rain,\\
1181-- \\ type \\"potion\\" or \\"quit\\""
1182-- _ <- runStateT ('runStream' game) 60
1186-- You can also find the source of this example in the examples directory as
1187-- "AcidRain.hs". It has been adapted from Gabriel's
1188-- <https://hackage.haskell.org/package/pipes-concurrency-2.0.8/docs/Pipes-Concurrent-Tutorial.html pipes-concurrency>
1190-- This is much simpler compared to the pipes version because of the builtin
1191-- concurrency in streamly. You can also find a SDL based reactive programming
1192-- example adapted from Yampa in "Streamly.Examples.CirclingSquare".
1196-- Streamly is highly optimized for performance, it is designed for serious
1197-- high performing, concurrent and scalable applications. We have created the
1198-- <https://hackage.haskell.org/package/streaming-benchmarks streaming-benchmarks>
1199-- package which is specifically and carefully designed to measure the
1200-- performance of Haskell streaming libraries fairly and squarely in the right
1201-- way. Streamly performs at par or even better than most streaming libraries
1202-- for serial operations even though it needs to deal with the concurrency
1207-- We can use @unfoldr@ and @uncons@ to convert one streaming type to another.
1209-- Interop with @vector@:
1213-- import qualified Streamly.Prelude as S
1214-- import qualified Data.Vector.Fusion.Stream.Monadic as V
1217-- -- streamly to vector
1218-- V.toList (V.unfoldrM S.uncons (S.fromFoldable [1..3])) >>= print
1220-- -- vector to streamly
1221-- S.toList (S.unfoldrM unconsV (V.fromList [1..3])) >>= print
1227-- then return Nothing
1230-- return $ Just (h, V.tail v)
1233-- Interop with @pipes@:
1237-- import qualified "Streamly.Prelude" as S
1238-- import qualified Pipes as P
1239-- import qualified Pipes.Prelude as P
1242-- -- streamly to pipe
1243-- P.toListM (P.unfoldr unconsS (S.'fromFoldable' [1..3])) >>= print
1245-- -- pipe to streamly
1246-- S.'toList' (S.'unfoldrM' unconsP (P.each [1..3])) >>= print
1249-- -- Adapt P.next to return a Maybe instead of Either
1250-- unconsP p = P.next p >>= either (\\_ -> return Nothing) (return . Just)
1252-- -- Adapt S.uncons to return an Either instead of Maybe
1253-- unconsS s = S.'uncons' s >>= maybe (return $ Left ()) (return . Right)
1256-- Interop with @streaming@:
1260-- import qualified "Streamly.Prelude" as S
1261-- import qualified Streaming as SG
1262-- import qualified Streaming.Prelude as SG
1265-- -- streamly to streaming
1266-- SG.toList (SG.unfoldr unconsS (S.'fromFoldable' [1..3])) >>= print
1268-- -- streaming to streamly
1269-- S.'toList' (S.unfoldrM SG.uncons (SG.each [1..3])) >>= print
1273-- -- Adapt S.uncons to return an Either instead of Maybe
1274-- unconsS s = S.'uncons' s >>= maybe (return $ Left ()) (return . Right)
1277-- Interop with @conduit@:
1281-- import qualified "Streamly.Prelude" as S
1282-- import qualified Data.Conduit as C
1283-- import qualified Data.Conduit.List as C
1284-- import qualified Data.Conduit.Combinators as C
1287-- -- streamly to conduit
1288-- C.runConduit (C.unfoldM S.'uncons' (S.'fromFoldable' [1..3]) C..| C.sinkList) >>= print
1290-- -- It seems there is no way out of a conduit as it does not provide an
1291-- -- uncons or a tail function.
1296-- List transformers and logic programming monads also provide a product style
1297-- composition similar to streamly, however streamly generalizes it with the
1298-- time dimension; allowing streams to be composed in an asynchronous and
1299-- concurrent fashion in many different ways. It also provides multiple
1300-- alternative ways of composing streams e.g. serial, interleaved or
1303-- This seemingly simple addition of asynchronicity and concurrency to product
1304-- style streaming composition unifies a number of disparate abstractions into
1305-- one powerful, concise and elegant abstraction. A wide variety of
1306-- programming problems can be solved elegantly with this abstraction. In
1307-- particular, it unifies three major programming domains namely
1308-- non-deterministic (logic) programming, concurrent programming and functional
1309-- reactive programming. In other words, you can do everything with this one
1310-- abstraction that you could do with the popular libraries listed under these
1311-- categories in the list below.
1314-- +-----------------+----------------+
1315-- | Non-determinism | <https://hackage.haskell.org/package/pipes pipes> |
1316-- | +----------------+
1317-- | | <https://hackage.haskell.org/package/list-t list-t> |
1318-- | +----------------+
1319-- | | <https://hackage.haskell.org/package/logict logict> |
1320-- +-----------------+----------------+
1321-- | Streaming | <https://hackage.haskell.org/package/vector vector> |
1322-- | +----------------+
1323-- | | <https://hackage.haskell.org/package/streaming streaming> |
1324-- | +----------------+
1325-- | | <https://hackage.haskell.org/package/pipes pipes> |
1326-- | +----------------+
1327-- | | <https://hackage.haskell.org/package/conduit conduit> |
1328-- +-----------------+----------------+
1329-- | Concurrency | <https://hackage.haskell.org/package/async async> |
1330-- | +----------------+
1331-- | | <https://hackage.haskell.org/package/transient transient> |
1332-- +-----------------+----------------+
1333-- | FRP | <https://hackage.haskell.org/package/Yampa Yampa> |
1334-- | +----------------+
1335-- | | <https://hackage.haskell.org/package/dunai dunai> |
1336-- | +----------------+
1337-- | | <https://hackage.haskell.org/package/reflex reflex> |
1338-- +-----------------+----------------+
1341-- Streamly is a list-transformer. It provides all the functionality provided
1342-- by any of the list transformer and logic programming packages listed above.
1343-- In addition, Streamly naturally integrates the concurrency dimension to the
1344-- basic list transformer functionality.
1346-- When it comes to streaming, in terms of the streaming API streamly is almost
1347-- identical to the vector package. Streamly, vector and streaming packages all
1348-- represent a stream as data and are therefore similar in the fundamental
1349-- approach to streaming. The fundamental difference is that streamly adds
1350-- concurrency support and the monad instance provides concurrent looping.
1351-- Other streaming libraries like pipes, conduit and machines represent and
1352-- compose stream processors rather than the stream data and therefore fall in
1353-- another class of streaming libraries and have comparatively more complicated
1356-- When it comes to concurrency, streamly can do everything that the @async@
1357-- package can do and more. async provides applicative concurrency whereas
1358-- streamly provides both applicative and monadic concurrency. The
1359-- 'ZipParallel' type behaves like the applicative instance of async. In
1360-- comparison to transient streamly has a first class streaming interface and
1361-- is a monad transformer that can be used universally in any Haskell monad
1362-- transformer stack. Streamly was in fact originally inspired by the
1363-- concurrency implementation in @transient@ though it has no resemblence with
1364-- that and takes a lazy pull approach versus transient's strict push approach.
1366-- The non-determinism, concurrency and streaming combination make streamly a
1367-- strong FRP capable library as well. FRP is fundamentally stream of events
1368-- that can be processed concurrently. The example in this tutorial as well as
1369-- the "Streamly.Examples.CirclingSquare" example from Yampa demonstrate the
1370-- basic FRP capability of streamly. In core concepts streamly is strikingly
1371-- similar to @dunai@. dunai was designed from a FRP perspective and streamly
1372-- was originally designed from a concurrency perspective. However, both have
1373-- similarity at the core.
1377-- * Read the documentation of "Streamly" module
1378-- * Read the documentation of "Streamly.Prelude" module
1379-- * See the examples in the "examples" directory of the package
1380-- * 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