on 00dcf03 help sign in
streamly/src/Streamly/Tutorial.hs
1043 lines 35 kB history raw
1{-# OPTIONS_GHC -fno-warn-unused-imports #-}
2-- |
3-- Module : Streamly.Tutorial
4-- Copyright : (c) 2017 Harendra Kumar
5--
6-- License : BSD3
7-- Maintainer : harendra.kumar@gmail.com
8--
9-- Streamly, short for stream concurrently, combines the essence of
10-- non-determinism, streaming and concurrency in functional programming.
11-- Concurrent and non-concurrent applications are almost indistinguisable,
12-- concurrency capability does not at all impact the performance of
13-- non-concurrent case.
14-- Streaming enables writing modular, composable and scalable applications with
15-- ease and concurrency allows you to make them scale and perform well.
16-- Streamly enables writing concurrent applications without being aware of
17-- threads or synchronization. No explicit thread control is needed, where
18-- applicable the concurrency rate is automatically controlled based on the
19-- demand by the consumer. However, combinators are provided to fine tune the
20-- concurrency control.
21-- Streaming and concurrency together enable expressing reactive applications
22-- conveniently. See "Streamly.Examples" for a simple SDL based FRP example.
23--
24-- Streamly streams are very much like the Haskell lists and most of the
25-- functions that work on lists have a counterpart that works on streams.
26-- However, streamly streams can be generated, consumed or combined
27-- concurrently. In this tutorial we will go over the basic concepts and how to
28-- use the library. The documentation of @Streamly@ module has more details on
29-- core APIs. For more APIs for constructing, folding, filtering, mapping and
30-- zipping etc. see the documentation of "Streamly.Prelude" module. For
31-- examples and other ways to use the library see the module
32-- "Streamly.Examples" as well.
34module Streamly.Tutorial
35 (
36 -- * Streams
37 -- $streams
39 -- ** Generating Streams
40 -- $generating
42 -- ** Eliminating Streams
43 -- $eliminating
45 -- * Combining Streams
46 -- $combining
48 -- ** Semigroup Style
49 -- $semigroup
51 -- *** Serial composition ('<>')
52 -- $serial
54 -- *** Async composition ('<|')
55 -- $parallel
57 -- *** Interleaved composition ('<=>')
58 -- $interleaved
60 -- *** Fair Concurrent composition ('<|>')
61 -- $fairParallel
63 -- *** Custom composition
64 -- $custom
66 -- ** Monoid Style
67 -- $monoid
69 -- * Transforming Streams
70 -- $transforming
72 -- ** Monad
73 -- $monad
75 -- *** Serial Composition ('StreamT')
76 -- $regularSerial
78 -- *** Async Composition ('AsyncT')
79 -- $concurrentNesting
81 -- *** Interleaved Composition ('InterleavedT')
82 -- $interleavedNesting
84 -- *** Fair Concurrent Composition ('ParallelT')
85 -- $fairlyConcurrentNesting
87 -- *** Exercise
88 -- $monadExercise
90 -- ** Applicative
91 -- $applicative
93 -- ** Functor
94 -- $functor
96 -- * Zipping Streams
97 -- $zipping
99 -- ** Serial Zipping
100 -- $serialzip
102 -- ** Parallel Zipping
103 -- $parallelzip
105 -- * Summary of Compositions
106 -- $compositionSummary
108 -- * Concurrent Programming
109 -- $concurrent
111 -- * Reactive Programming
112 -- $reactive
114 -- * Performance
115 -- $performance
117 -- * Interoperation with Streaming Libraries
118 -- $interop
120 -- * Comparison with Existing Packages
121 -- $comparison
122 )
123where
125import Streamly
126import Streamly.Prelude
127import Data.Semigroup
128import Control.Applicative
129import Control.Monad
130import Control.Monad.IO.Class (MonadIO(..))
131import Control.Monad.Trans.Class (MonadTrans (lift))
133-- $streams
134--
135-- Streamly provides many different stream types depending on the desired
136-- composition style. The simplest type is 'StreamT'. 'StreamT' is a monad
137-- transformer, the type @StreamT m a@ represents a stream of values of type
138-- 'a' in some underlying monad 'm'. For example, @StreamT IO Int@ is a stream
139-- of 'Int' in 'IO' monad.
141-- $generating
142--
143-- Pure values can be placed into the stream type using 'return' or 'pure'.
144-- Effects in the IO monad can be lifted to the stream type using the 'liftIO'
145-- combinator. In a transformer stack we can lift actions from the lower monad
146-- using the 'lift' combinator. Some examples of streams with a single element:
147--
148-- @
149-- return 1 :: 'StreamT' IO Int
150-- @
151-- @
152-- liftIO $ putStrLn "Hello world!" :: 'StreamT' IO ()
153-- @
154--
155-- We can combine streams using '<>' to create streams of many elements:
156--
157-- @
158-- return 1 <> return 2 <> return 3 :: 'StreamT' IO Int
159-- @
160--
161-- For more ways to construct or generate a stream see the module
162-- "Streamly.Prelude".
164-- $eliminating
165--
166-- 'runStreamT' runs a composed 'StreamT' computation, lowering the type into
167-- the underlying monad and discarding the result stream:
168--
169-- @
170-- import "Streamly"
171--
172-- main = 'runStreamT' $ liftIO $ putStrLn "Hello world!"
173-- @
174--
175-- 'toList' runs a stream computation and collects the result stream in a list
176-- in the underlying monad. 'toList' is a polymorphic function that works on
177-- multiple stream types belonging to the class 'Streaming'. Therefore, before
178-- you run a stream you need to tell how you want to interpret the stream by
179-- using one of the stream type combinators ('serially', 'asyncly', 'parallely'
180-- etc.). The combinator 'serially' is equivalent to annotating the type as @::
181-- StreamT@.
182--
183-- @
184-- import "Streamly"
185-- import "Streamly.Prelude"
186--
187-- main = do
188-- xs \<- 'toList' $ 'serially' $ return 1 <> return 2
189-- print xs
190-- @
191--
192-- For other ways to eliminate or fold a stream see the module
193-- "Streamly.Prelude".
195-- $semigroup
196-- Streams of the same type can be combined into a composite stream in many
197-- different ways using one of the semigroup style binary composition operators
198-- i.e. '<>', '<=>', '<|', '<|>', 'mplus'. These operators work on all stream
199-- types ('StreamT', 'AsyncT' etc.) uniformly.
200--
201-- To illustrate the concurrent aspects, we will use the following @delay@
202-- function to introduce a delay specified in seconds.
203--
204-- @
205-- import "Streamly"
206-- import Control.Concurrent
207--
208-- delay n = liftIO $ do
209-- threadDelay (n * 1000000)
210-- tid \<- myThreadId
211-- putStrLn (show tid ++ ": Delay " ++ show n)
212-- @
214-- $serial
215--
216-- We have already seen, the '<>' operator. It composes two streams in series
217-- i.e. the first stream is completely exhausted and then the second stream is
218-- processed. The following example prints the sequence 3, 2, 1 and takes a
219-- total of 6 seconds because everything is serial:
220--
221-- @
222-- main = 'runStreamT' $ delay 3 <> delay 2 <> delay 1
223-- @
224-- @
225-- ThreadId 36: Delay 3
226-- ThreadId 36: Delay 2
227-- ThreadId 36: Delay 1
228-- @
230-- $interleaved
231-- The '<=>' operator is serial like '<>' but it interleaves the two streams
232-- i.e. it yields one element from the first stream and then one element from
233-- the second stream, and so on. The following example prints the sequence 1,
234-- 3, 2, 4 and takes a total of 10 seconds because everything is serial:
235--
236-- @
237-- main = 'runStreamT' $ (delay 1 <> delay 2) '<=>' (delay 3 <> delay 4)
238-- @
239-- @
240-- ThreadId 36: Delay 1
241-- ThreadId 36: Delay 3
242-- ThreadId 36: Delay 2
243-- ThreadId 36: Delay 4
244-- @
245--
246-- Note that this operator cannot be used to fold infinite containers since it
247-- requires preserving the state until a stream is finished. To be clear, it
248-- can combine infinite streams but not infinite number of streams.
250-- $parallel
251--
252-- The '<|' operator can run both computations concurrently, /when needed/.
253-- In the following example since the first computation blocks we start the
254-- next one in a separate thread and so on:
255--
256-- @
257-- main = 'runStreamT' $ delay 3 '<|' delay 2 '<|' delay 1
258-- @
259-- @
260-- ThreadId 42: Delay 1
261-- ThreadId 41: Delay 2
262-- ThreadId 40: Delay 3
263-- @
264--
265-- This is the concurrent version of the '<>' operator. The computations are
266-- triggered in the same order as '<>' except that they are concurrent. When
267-- we have a tree of computations composed using this operator, the tree is
268-- traversed in DFS style just like '<>'.
269--
270-- @
271-- main = 'runStreamT' $ (p 1 '<|' p 2) '<|' (p 3 '<|' p 4)
272-- where p = liftIO . print
273-- @
274-- @
275-- 1
276-- 2
277-- 3
278-- 4
279-- @
280--
281-- Concurrency provided by this operator is demand driven. The second
282-- computation is run concurrently with the first only if the first computation
283-- is not producing enough output to keep the stream consumer busy otherwise
284-- the second computation is run serially after the previous one. The number of
285-- concurrent threads is adapted dynamically based on the pull rate of the
286-- consumer of the stream.
287-- As you can see, in the following example the computations are run in a
288-- single thread one after another, because none of them blocks. However, if
289-- the thread consuming the stream were faster than the producer then it would
290-- have started parallel threads for each computation to keep up even if none
291-- of them blocks:
292--
293-- @
294-- main = 'runStreamT' $ traced (sqrt 9) '<|' traced (sqrt 16) '<|' traced (sqrt 25)
295-- where traced m = liftIO (myThreadId >>= print) >> m
296-- @
297-- @
298-- ThreadId 40
299-- ThreadId 40
300-- ThreadId 40
301-- @
302--
303-- Since the concurrency provided by this operator is demand driven it cannot
304-- be used when the composed computations have timers that are relative to each
305-- other because all computations may not be started at the same time and
306-- therefore timers in all of them may not start at the same time. When
307-- relative timing among all computations is important or when we need to start
308-- all computations at once for some reason '<|>' must be used instead.
309-- However, '<|' is useful in situations when we want to optimally utilize the
310-- resources and we know that the computations can run in parallel but we do
311-- not care if they actually run in parallel or not, that decision is left to
312-- the scheduler. Also, note that this operator can be used to fold infinite
313-- containers in contrast to '<|>', because it does not require us to run all
314-- of them at the same time.
315--
316-- The left bias (or the DFS style) of the operator '<|' is suggested by its
317-- shape. You can also think of this as an unbalanced version of the fairly
318-- parallel operator '<|>'.
320-- $fairParallel
321--
322-- The 'Alternative' composition operator '<|>', like '<|', runs the composed
323-- computations concurrently. However, unlike '<|' it runs all of the
324-- computations in fairly parallel manner using a round robin scheduling
325-- mechanism. This can be considered as the concurrent version of the fairly
326-- interleaved serial operation '<=>'. Note that this cannot be used on
327-- infinite containers, as it will lead to an infinite sized scheduling queue.
328--
329-- The following example sends a query to three search engines in parallel and
330-- prints the name of the search engine as a response arrives:
331--
332-- @
333-- import "Streamly"
334-- import Network.HTTP.Simple
335--
336-- main = 'runStreamT' $ google \<|> bing \<|> duckduckgo
337-- where
338-- google = get "https://www.google.com/search?q=haskell"
339-- bing = get "https://www.bing.com/search?q=haskell"
340-- duckduckgo = get "https://www.duckduckgo.com/?q=haskell"
341-- get s = liftIO (httpNoBody (parseRequest_ s) >> putStrLn (show s))
342-- @
344-- $custom
345--
346-- The 'async' API can be used to create references to asynchronously running
347-- stream computations. We can then use 'uncons' to explore the streams
348-- arbitrarily and then recompose individual elements to create a new stream.
349-- This way we can dynamically decide which stream to explore at any given
350-- time. Take an example of a merge sort of two sorted streams. We need to
351-- keep consuming items from the stream which has the lowest item in the sort
352-- order. This can be achieved using async references to streams. See
353-- "Streamly.Examples.MergeSortedStreams".
355-- $monoid
356--
357-- Each of the semigroup compositions described has an identity that can be
358-- used to fold a possibly empty container. An empty stream is represented by
359-- 'nil' which can be represented in various standard forms as 'mempty',
360-- 'empty' or 'mzero'.
361-- Some fold utilities are also provided by the library for convenience:
362--
363-- * 'foldWith' folds a 'Foldable' container of stream computations using the
364-- given composition operator.
365-- * 'foldMapWith' folds like foldWith but also maps a function before folding.
366-- * 'forEachWith' is like foldMapwith but the container argument comes before
367-- the function argument.
368-- * The 'each' primitive from "Streamly.Prelude" folds a 'Foldable' container
369-- using the '<>' operator:
370--
371-- All of the following are equivalent:
372--
373-- @
374-- import "Streamly"
375-- import "Streamly.Prelude"
376--
377-- main = do
378-- 'toList' . 'serially' $ 'foldWith' (<>) (map return [1..10]) >>= print
379-- 'toList' . 'serially' $ 'foldMapWith' (<>) return [1..10] >>= print
380-- 'toList' . 'serially' $ 'forEachWith' (<>) [1..10] return >>= print
381-- 'toList' . 'serially' $ 'each' [1..10] >>= print
382-- @
384-- $transforming
385--
386-- The previous section discussed ways to merge the elements of two streams
387-- without doing any transformation on them. In this section we will explore
388-- how to transform streams using 'Functor', 'Applicative' or 'Monad' style
389-- compositions. The applicative and monad composition of all 'Streaming' types
390-- behave exactly the same way as a list transformer. For simplicity of
391-- illustration we are using streams of pure values in the following examples.
392-- However, the real application of streams arises when these streams are
393-- generated using monadic actions.
395-- $monad
396--
397-- In functional programmer's parlance the 'Monad' instance of 'Streaming'
398-- types implement non-determinism, exploring all possible combination of
399-- choices from both the streams. From an imperative programmer's point of view
400-- it behaves like nested loops i.e. for each element in the first stream and
401-- for each element in the second stream apply the body of the loop. If you are
402-- familiar with list transformer this behavior is exactly the same as that of
403-- a list transformer.
404--
405-- Just like we saw in sum style compositions earlier, monadic composition also
406-- has multiple variants each of which exactly corresponds to one of the sum
407-- style composition variant.
409-- $regularSerial
410--
411-- When we interpret the monadic composition as 'StreamT' we get a standard
412-- list transformer like serial composition.
413--
414-- @
415-- import "Streamly"
416-- import "Streamly.Prelude"
417--
418-- main = 'runStreamT' $ do
419-- x <- 'each' [3,2,1]
420-- delay x
421-- @
422-- @
423-- ThreadId 30: Delay 3
424-- ThreadId 30: Delay 2
425-- ThreadId 30: Delay 1
426-- @
427--
428-- As you can see the code after the @each@ statement is run three times, once
429-- for each value of @x@. All the three iterations are serial and run in the
430-- same thread one after another. When compared to imperative programming, this
431-- can also be viewed as a @for@ loop with three iterations.
432--
433-- A console echo loop copying standard input to standard output can simply be
434-- written like this:
435--
436-- @
437-- import "Streamly"
438-- import Data.Semigroup (cycle1)
439--
440-- main = 'runStreamT' $ cycle1 (liftIO getLine) >>= liftIO . putStrLn
441-- @
442--
443-- When multiple streams are composed using this style they nest in a DFS
444-- manner i.e. nested iterations of an iteration are executed before we proceed
445-- to the next iteration at higher level. This behaves just like nested @for@
446-- loops in imperative programming.
447--
448-- @
449-- import "Streamly"
450-- import "Streamly.Prelude"
451--
452-- main = 'runStreamT' $ do
453-- x <- 'each' [1,2]
454-- y <- 'each' [3,4]
455-- liftIO $ putStrLn $ show (x, y)
456-- @
457-- @
458-- (1,3)
459-- (1,4)
460-- (2,3)
461-- (2,4)
462-- @
463--
464-- You will also notice that this is the monadic equivalent of the sum style
465-- composition using '<>'.
467-- $concurrentNesting
468--
469-- When we interpret the monadic composition as 'AsyncT' we get a /concurrent/
470-- list-transformer like composition. Multiple monadic continuations (or loop
471-- iterations) may be started concurrently. Concurrency is demand driven
472-- i.e. more concurrent iterations are started only if the previous iterations
473-- are not able to produce enough output for the consumer of the output stream.
474-- This is the concurrent version of 'StreamT'.
475--
476-- @
477-- import "Streamly"
478-- import "Streamly.Prelude"
479--
480-- main = 'runAsyncT' $ do
481-- x <- 'each' [3,2,1]
482-- delay x
483-- @
484-- @
485-- ThreadId 40: Delay 1
486-- ThreadId 39: Delay 2
487-- ThreadId 38: Delay 3
488-- @
489--
490-- As you can see the code after the @each@ statement is run three times, once
491-- for each value of @x@. All the three iterations are concurrent and run in
492-- different threads. The iteration with least delay finishes first. When
493-- compared to imperative programming, this can be viewed as a @for@ loop
494-- with three concurrent iterations.
495--
496-- Concurrency is demand driven just as in the case of '<|'. When multiple
497-- streams are composed using this style the iterations are triggered in a DFS
498-- manner just like 'StreamT' i.e. nested iterations are executed before we
499-- proceed to the next iteration at higher level. However, unlike 'StreamT'
500-- more than one iterations may be started concurrently, and based on the
501-- demand from the consumer.
502--
503-- @
504-- import "Streamly"
505-- import "Streamly.Prelude"
506--
507-- main = 'runAsyncT' $ do
508-- x <- 'each' [1,2]
509-- y <- 'each' [3,4]
510-- liftIO $ putStrLn $ show (x, y)
511-- @
512-- @
513-- (1,3)
514-- (1,4)
515-- (2,3)
516-- (2,4)
517-- @
518--
519-- You will notice that this is the monadic equivalent of the '<|' style
520-- sum composition. The same caveats apply to this as the '<|' operation.
522-- $interleavedNesting
523--
524-- When we interpret the monadic composition as 'InterleavedT' we get a serial
525-- but fairly interleaved list-transformer like composition. The monadic
526-- continuations or iterations of the outer loop are fairly interleaved with
527-- the continuations or iterations of the inner loop.
528--
529-- @
530-- import "Streamly"
531-- import "Streamly.Prelude"
532--
533-- main = 'runInterleavedT' $ do
534-- x <- 'each' [1,2]
535-- y <- 'each' [3,4]
536-- liftIO $ putStrLn $ show (x, y)
537-- @
538-- @
539-- (1,3)
540-- (2,3)
541-- (1,4)
542-- (2,4)
543-- @
544--
545-- You will notice that this is the monadic equivalent of the '<=>' style
546-- sum composition. The same caveats apply to this as the '<=>' operation.
548-- $fairlyConcurrentNesting
549--
550-- When we interpret the monadic composition as 'ParallelT' we get a
551-- /concurrent/ list-transformer like composition just like 'AsyncT'. The
552-- difference is that this is fully parallel with all iterations starting
553-- concurrently instead of the demand driven concurrency of 'AsyncT'.
554--
555-- @
556-- import "Streamly"
557-- import "Streamly.Prelude"
558--
559-- main = 'runParallelT' $ do
560-- x <- 'each' [3,2,1]
561-- delay x
562-- @
563-- @
564-- ThreadId 40: Delay 1
565-- ThreadId 39: Delay 2
566-- ThreadId 38: Delay 3
567-- @
568--
569-- You will notice that this is the monadic equivalent of the '<|>' style
570-- sum composition. The same caveats apply to this as the '<|>' operation.
572-- $monadExercise
573--
574-- The streamly code is usually written in a way that is agnostic of the
575-- specific monadic composition type. We use a polymorphic type with a
576-- 'Streaming' type class constraint. When running the stream we can choose the
577-- specific mode of composition. For example look at the following code.
578--
579-- @
580-- import "Streamly"
581-- import "Streamly.Prelude"
582--
583--
584-- composed :: 'Streaming' t => t m a
585-- composed = do
586-- sz <- sizes
587-- cl <- colors
588-- sh <- shapes
589-- liftIO $ putStrLn $ show (sz, cl, sh)
590--
591-- where
592--
593-- sizes = 'each' [1, 2, 3]
594-- colors = 'each' ["red", "green", "blue"]
595-- shapes = 'each' ["triangle", "square", "circle"]
596-- @
597--
598-- Now we can interpret this in whatever way we want:
599--
600-- @
601-- main = 'runStreamT' composed
602-- main = 'runAsyncT' composed
603-- main = 'runInterleavedT' composed
604-- main = 'runParallelT' composed
605-- @
606--
607-- Equivalently, we can also write it using the type adapter combinators, like
608-- this:
609--
610-- @
611-- main = 'runStreaming' $ 'serially' $ composed
612-- main = 'runStreaming' $ 'asyncly' $ composed
613-- main = 'runStreaming' $ 'interleaving' $ composed
614-- main = 'runStreaming' $ 'parallely' $ composed
615-- @
616--
617-- As an exercise try to figure out the output of this code for each mode of
618-- composition.
620-- $functor
621--
622-- 'fmap' transforms a stream by mapping a function on all elements of the
623-- stream. The functor instance of each stream type defines 'fmap' to be
624-- precisely the same as 'liftM', and therefore 'fmap' is always serial
625-- irrespective of the type. For concurrent mapping, alternative versions of
626-- 'fmap', namely, 'asyncMap' and 'parMap' are provided.
627--
628-- @
629-- import "Streamly"
630--
631-- main = ('toList' $ 'serially' $ fmap show $ 'each' [1..10]) >>= print
632-- @
633--
634-- Also see the 'mapM' and 'sequence' functions for mapping actions, in the
635-- "Streamly.Prelude" module.
637-- $applicative
638--
639-- Applicative is precisely the same as the 'ap' operation of 'Monad'. For
640-- zipping and parallel applicatives separate types 'ZipStream' and 'ZipAsync'
641-- are provided.
642--
643-- The following example runs all iterations serially and takes a total 17
644-- seconds (1 + 3 + 4 + 2 + 3 + 4):
645--
646-- @
647-- import "Streamly"
648-- import "Streamly.Prelude"
649-- import Control.Concurrent
650--
651-- s1 = d 1 <> d 2
652-- s2 = d 3 <> d 4
653-- d n = delay n >> return n
654--
655-- main = ('toList' . 'serially' $ (,) \<$> s1 \<*> s2) >>= print
656-- @
657-- @
658-- ThreadId 36: Delay 1
659-- ThreadId 36: Delay 3
660-- ThreadId 36: Delay 4
661-- ThreadId 36: Delay 2
662-- ThreadId 36: Delay 3
663-- ThreadId 36: Delay 4
664-- [(1,3),(1,4),(2,3),(2,4)]
665-- @
666--
667-- Similalrly interleaving runs the iterations in an interleaved order but
668-- since it is serial it takes a total of 17 seconds:
669--
670-- @
671-- main = ('toList' . 'interleaving' $ (,) \<$> s1 \<*> s2) >>= print
672-- @
673-- @
674-- ThreadId 36: Delay 1
675-- ThreadId 36: Delay 3
676-- ThreadId 36: Delay 2
677-- ThreadId 36: Delay 3
678-- ThreadId 36: Delay 4
679-- ThreadId 36: Delay 4
680-- [(1,3),(2,3),(1,4),(2,4)]
681-- @
682--
683-- 'AsyncT' can run the iterations concurrently and therefore takes a total
684-- of 10 seconds (1 + 2 + 3 + 4):
685--
686-- @
687-- main = ('toList' . 'asyncly' $ (,) \<$> s1 \<*> s2) >>= print
688-- @
689-- @
690-- ThreadId 34: Delay 1
691-- ThreadId 36: Delay 2
692-- ThreadId 35: Delay 3
693-- ThreadId 36: Delay 3
694-- ThreadId 35: Delay 4
695-- ThreadId 36: Delay 4
696-- [(1,3),(2,3),(1,4),(2,4)]
697-- @
698--
699-- Similalrly 'ParallelT' as well can run the iterations concurrently and
700-- therefore takes a total of 10 seconds (1 + 2 + 3 + 4):
701--
702-- @
703-- main = ('toList' . 'parallely' $ (,) \<$> s1 \<*> s2) >>= print
704-- @
705-- @
706-- ThreadId 34: Delay 1
707-- ThreadId 36: Delay 2
708-- ThreadId 35: Delay 3
709-- ThreadId 36: Delay 3
710-- ThreadId 35: Delay 4
711-- ThreadId 36: Delay 4
712-- [(1,3),(2,3),(1,4),(2,4)]
713-- @
715-- $compositionSummary
716--
717-- The following table summarizes the types for monadic compositions and the
718-- operators for sum style compositions. This table captures the essence of
719-- streamly.
720--
721-- @
722-- +-----+--------------+------------+
723-- | | Serial | Concurrent |
724-- +=====+==============+============+
725-- | DFS | 'StreamT' | 'AsyncT' |
726-- | +--------------+------------+
727-- | | '<>' | '<|' |
728-- +-----+--------------+------------+
729-- | BFS | 'InterleavedT' | 'ParallelT' |
730-- | +--------------+------------+
731-- | | '<=>' | '<|>' |
732-- +-----+--------------+------------+
733-- @
735-- $zipping
736--
737-- Zipping is a special transformation where the corresponding elements of two
738-- streams are combined together using a zip function producing a new stream of
739-- outputs. Two different types are provided for serial and concurrent zipping.
740-- These types provide an applicative instance that zips the argument streams.
741-- Also see the zipping function in the "Streamly.Prelude" module.
743-- $serialzip
744--
745-- 'ZipStream' zips streams serially:
746--
747-- @
748-- import "Streamly"
749-- import "Streamly.Prelude"
750-- import Control.Concurrent
751--
752-- d n = delay n >> return n
753-- s1 = 'adapt' . 'serially' $ d 1 <> d 2
754-- s2 = 'adapt' . 'serially' $ d 3 <> d 4
755--
756-- main = ('toList' . 'zipping' $ (,) \<$> s1 \<*> s2) >>= print
757-- @
758--
759-- This takes total 10 seconds to zip, which is (1 + 2 + 3 + 4) since
760-- everything runs serially:
761--
762-- @
763-- ThreadId 29: Delay 1
764-- ThreadId 29: Delay 3
765-- ThreadId 29: Delay 2
766-- ThreadId 29: Delay 4
767-- [(1,3),(2,4)]
768-- @
770-- $parallelzip
771--
772-- 'ZipAsync' zips streams concurrently:
773--
774-- @
775-- import "Streamly"
776-- import "Streamly.Prelude"
777-- import Control.Concurrent
778-- import System.IO (stdout, hSetBuffering, BufferMode(LineBuffering))
779--
780-- d n = delay n >> return n
781-- s1 = 'adapt' . 'serially' $ d 1 <> d 2
782-- s2 = 'adapt' . 'serially' $ d 3 <> d 4
783--
784-- main = do
785-- liftIO $ hSetBuffering stdout LineBuffering
786-- ('toList' . 'zippingAsync' $ (,) \<$> s1 \<*> s2) >>= print
787-- @
788--
789-- This takes 7 seconds to zip, which is max (1,3) + max (2,4) because 1 and 3
790-- are produced concurrently, and 2 and 4 are produced concurrently:
791--
792-- @
793-- ThreadId 32: Delay 1
794-- ThreadId 32: Delay 2
795-- ThreadId 33: Delay 3
796-- ThreadId 33: Delay 4
797-- [(1,3),(2,4)]
798-- @
800-- $concurrent
801--
802-- When writing concurrent programs there are two distinct places where the
803-- programmer chooses the type of concurrency. First, when /generating/ a
804-- stream by combining other streams we can use one of the sum style operators
805-- to combine them concurrently or serially. Second, when /processing/ a stream
806-- in a monadic composition we can choose one of the monad composition types to
807-- choose the desired type of concurrency.
808--
809-- In the following example the squares of @x@ and @y@ are computed
810-- concurrently using the '<|' operator and the square roots of their sum are
811-- also computed concurrently by using the 'asyncly' combinator. We can choose
812-- different combinators e.g. '<>' and 'serially', to control the concurrency.
813--
814-- @
815-- import "Streamly"
816-- import "Streamly.Prelude" (toList)
817-- import Data.List (sum)
818--
819-- main = do
820-- z \<- 'toList'
821-- $ 'asyncly' -- Concurrent monadic processing (sqrt below)
822-- $ do
823-- x2 \<- 'forEachWith' ('<|') [1..100] $ -- Concurrent @"for"@ loop
824-- \\x -> return $ x * x -- body of the loop
825-- y2 \<- 'forEachWith' ('<|') [1..100] $
826-- \\y -> return $ y * y
827-- return $ sqrt (x2 + y2)
828-- print $ sum z
829-- @
830--
831-- You can see how this directly maps to the imperative style
832-- <https://en.wikipedia.org/wiki/OpenMP OpenMP> model, we use combinators
833-- and operators instead of the ugly pragmas.
834--
835-- For more concurrent programming examples see,
836-- "Streamly.Examples.ListDirRecursive", "Streamly.Examples.MergeSortedStreams"
837-- and "Streamly.Examples.SearchEngineQuery".
839-- $reactive
840--
841-- Reactive programming is nothing but concurrent streaming which is what
842-- streamly is all about. With streamly we can generate streams of events,
843-- merge streams that are generated concurrently and process events
844-- concurrently. We can do all this without any knowledge about the specifics
845-- of the implementation of concurrency. In the following example you will see
846-- that the code is just regular Haskell code without much streamly APIs used
847-- (active hyperlinks are the streamly APIs) and yet it is a reactive
848-- application.
849--
850--
851-- This application has two independent and concurrent sources of event
852-- streams, @acidRain@ and @userAction@. @acidRain@ continuously generates
853-- events that deteriorate the health of the game character. @userAction@ can
854-- be "potion" or "quit". When the user types "potion" the health improves and
855-- the game continues.
856--
857-- @
858-- {-\# LANGUAGE FlexibleContexts #-}
859--
860-- import "Streamly"
861-- import Control.Concurrent (threadDelay)
862-- import Control.Monad (when)
863-- import Control.Monad.State
864-- import Data.Semigroup (cycle1)
865--
866-- data Event = Harm Int | Heal Int | Quit deriving (Show)
867--
868-- userAction :: MonadIO m => 'StreamT' m Event
869-- userAction = cycle1 $ liftIO askUser
870-- where
871-- askUser = do
872-- command <- getLine
873-- case command of
874-- "potion" -> return (Heal 10)
875-- "quit" -> return Quit
876-- _ -> putStrLn "What?" >> askUser
877--
878-- acidRain :: MonadIO m => 'StreamT' m Event
879-- acidRain = cycle1 $ liftIO (threadDelay 1000000) >> return (Harm 1)
880--
881-- game :: ('MonadAsync' m, MonadState Int m) => 'StreamT' m ()
882-- game = do
883-- event \<- userAction \<|> acidRain
884-- case event of
885-- Harm n -> modify $ \\h -> h - n
886-- Heal n -> modify $ \\h -> h + n
887-- Quit -> fail "quit"
888--
889-- h <- get
890-- when (h <= 0) $ fail "You die!"
891-- liftIO $ putStrLn $ "Health = " ++ show h
892--
893-- main = do
894-- putStrLn "Your health is deteriorating due to acid rain,\\
895-- \\ type \\"potion\\" or \\"quit\\""
896-- _ <- runStateT ('runStreamT' game) 60
897-- return ()
898-- @
899--
900-- You can also find the source of this example in
901-- "Streamly.Examples.AcidRainGame". It has been adapted from Gabriel's
902-- <https://hackage.haskell.org/package/pipes-concurrency-2.0.8/docs/Pipes-Concurrent-Tutorial.html pipes-concurrency>
903-- package.
904-- This is much simpler compared to the pipes version because of the builtin
905-- concurrency in streamly. You can also find a SDL based reactive programming
906-- example adapted from Yampa in "Streamly.Examples.CirclingSquare".
908-- $performance
909--
910-- Streamly is highly optimized for performance, it is designed for serious
911-- high performing, concurrent and scalable applications. We have created the
912-- <https://hackage.haskell.org/package/streaming-benchmarks streaming-benchmarks>
913-- package which is specifically and carefully designed to measure the
914-- performance of Haskell streaming libraries fairly and squarely in the right
915-- way. Streamly performs at par or even better than most streaming libraries
916-- for common operations even though it needs to deal with the concurrency
917-- capability.
919-- $interop
920--
921-- We can use @unfoldr@ and @uncons@ to convert one streaming type to another.
922-- We will assume the following common code to be available in the examples
923-- demonstrated below.
924--
925-- @
926-- import "Streamly"
927-- import "Streamly.Prelude"
928-- import System.IO (stdin)
929--
930-- -- Adapt uncons to return an Either instead of Maybe
931-- unconsE s = 'uncons' s >>= maybe (return $ Left ()) (return . Right)
932-- stdinLn = 'serially' $ 'fromHandle' stdin
933-- @
934--
935-- Interop with @pipes@:
936--
937-- @
938-- import qualified Pipes as P
939-- import qualified Pipes.Prelude as P
940--
941-- main = do
942-- -- streamly to pipe
943-- P.runEffect $ P.for (P.unfoldr unconsE stdinLn) (lift . putStrLn)
944--
945-- -- pipe to streamly
946-- -- Adapt P.next to return a Maybe instead of Either
947-- let nextM p = P.next p >>= either (\\_ -> return Nothing) (return . Just)
948-- 'runStreamT' $ 'unfoldrM' nextM P.stdinLn >>= lift . putStrLn
949-- @
950--
951-- Interop with @streaming@:
952--
953-- @
954-- import qualified Streaming as S
955-- import qualified Streaming.Prelude as S
956--
957-- main = do
958-- -- streamly to streaming
959-- S.stdoutLn $ S.unfoldr unconsE stdinLn
960--
961-- -- streaming to streamly
962-- 'runStreamT' $ unfoldrM S.uncons S.stdinLn >>= lift . putStrLn
963--
964-- @
965--
966-- Interop with @conduit@:
967--
968-- @
969-- import qualified Data.Conduit as C
970-- import qualified Data.Conduit.List as C
971-- import qualified Data.Conduit.Combinators as C
972--
973-- -- streamly to conduit
974-- main = (C.unfoldM 'uncons' stdinLn) C.$$ C.print
975-- @
977-- $comparison
978--
979-- Streamly unifies non-determinism, streaming, concurrency and FRP
980-- functionality that is otherwise covered by several disparate packages, and
981-- it does that with a surprisingly concise API. Here is a list of popular and
982-- well-known packages in all these areas:
983--
984-- @
985-- +-----------------+----------------+
986-- | Non-determinism | <https://hackage.haskell.org/package/list-t list-t> |
987-- | +----------------+
988-- | | <https://hackage.haskell.org/package/logict logict> |
989-- +-----------------+----------------+
990-- | Streaming | <https://hackage.haskell.org/package/streaming streaming> |
991-- | +----------------+
992-- | | <https://hackage.haskell.org/package/conduit conduit> |
993-- | +----------------+
994-- | | <https://hackage.haskell.org/package/pipes pipes> |
995-- | +----------------+
996-- | | <https://hackage.haskell.org/package/simple-conduit simple-conduit> |
997-- +-----------------+----------------+
998-- | Concurrency | <https://hackage.haskell.org/package/async async> |
999-- | +----------------+
1000-- | | <https://hackage.haskell.org/package/transient transient> |
1001-- +-----------------+----------------+
1002-- | FRP | <https://hackage.haskell.org/package/Yampa Yampa> |
1003-- | +----------------+
1004-- | | <https://hackage.haskell.org/package/dunai dunai> |
1005-- | +----------------+
1006-- | | <https://hackage.haskell.org/package/reflex reflex> |
1007-- +-----------------+----------------+
1008-- @
1010-- Streamly covers all the functionality provided by both the non-determinism
1011-- packages listed above and provides better performance in comparison to
1012-- those. In fact, at the core streamly is a list transformer but it naturally
1013-- integrates the concurrency dimension to the basic list transformer
1014-- functionality.
1016-- When it comes to streaming, in terms of core concepts, @simple-conduit@ is
1017-- the package that is closest to streamly if we set aside the concurrency
1018-- dimension, both are streaming packages with list transformer like monad
1019-- composition. However, in terms of API @streamly@ is more like the @streaming@
1020-- package. Streamly can be used to achieve more or less the functionality
1021-- provided by any of the streaming packages listed above. The types and API of
1022-- streamly are much simpler in comparison to conduit and pipes. It is more or
1023-- less like the standard Haskell list APIs.
1025-- When it comes to concurrency, streamly can do everything that the @async@
1026-- package can do and more. async provides applicative concurrency whereas
1027-- streamly provides both applicative and monadic concurrency. The 'ZipAsync'
1028-- type behaves like the applicative instance of async. This work was
1029-- originally inspired by the concurrency implementation in @transient@ though
1030-- it has no resemblence with that. Streamly provides concurrency as transient
1031-- does but in a sort of dual manner, it can lazily stream the output. In
1032-- comparison to transient streamly has a first class streaming interface and
1033-- is a monad transformer that can be used universally in any Haskell monad
1034-- transformer stack.
1036-- The non-determinism, concurrency and streaming combination make streamly a
1037-- strong FRP capable library as well. FRP is fundamentally stream of events
1038-- that can be processed concurrently. The example in this tutorial as well as
1039-- the "Streamly.Examples.CirclingSquare" example from Yampa demonstrate the
1040-- basic FRP capability of streamly. In core concepts streamly is strikingly
1041-- similar to @dunai@. dunai was designed from a FRP perspective and streamly
1042-- was originally designed from a concurrency perspective. However, both have
1043-- similarity at the core.