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, 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.
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
39 -- ** Generating Streams
42 -- ** Eliminating Streams
45 -- * Combining Streams
51 -- *** Serial composition ('<>')
54 -- *** Async composition ('<|')
57 -- *** Interleaved composition ('<=>')
60 -- *** Fair Concurrent composition ('<|>')
63 -- *** Custom composition
69 -- * Transforming Streams
75 -- *** Serial Composition ('StreamT')
78 -- *** Async Composition ('AsyncT')
81 -- *** Interleaved Composition ('InterleavedT')
82 -- $interleavedNesting
84 -- *** Fair Concurrent Composition ('ParallelT')
85 -- $fairlyConcurrentNesting
102 -- ** Parallel Zipping
105 -- * Summary of Compositions
106 -- $compositionSummary
108 -- * Concurrent Programming
111 -- * Reactive Programming
117 -- * Interoperation with Streaming Libraries
120 -- * Comparison with Existing Packages
126import Streamly.Prelude
128import Control.Applicative
130import Control.Monad.IO.Class (MonadIO(..))
131import Control.Monad.Trans.Class (MonadTrans (lift))
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.
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:
149-- return 1 :: 'StreamT' IO Int
152-- liftIO $ putStrLn "Hello world!" :: 'StreamT' IO ()
155-- We can combine streams using '<>' to create streams of many elements:
158-- return 1 <> return 2 <> return 3 :: 'StreamT' IO Int
161-- For more ways to construct or generate a stream see the module
162-- "Streamly.Prelude".
166-- 'runStreamT' runs a composed 'StreamT' computation, lowering the type into
167-- the underlying monad and discarding the result stream:
172-- main = 'runStreamT' $ liftIO $ putStrLn "Hello world!"
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 @::
185-- import "Streamly.Prelude"
188-- xs \<- 'toList' $ 'serially' $ return 1 <> return 2
192-- For other ways to eliminate or fold a stream see the module
193-- "Streamly.Prelude".
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.
201-- To illustrate the concurrent aspects, we will use the following @delay@
202-- function to introduce a delay specified in seconds.
206-- import Control.Concurrent
208-- delay n = liftIO $ do
209-- threadDelay (n * 1000000)
211-- putStrLn (show tid ++ ": Delay " ++ show n)
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:
222-- main = 'runStreamT' $ delay 3 <> delay 2 <> delay 1
225-- ThreadId 36: Delay 3
226-- ThreadId 36: Delay 2
227-- ThreadId 36: Delay 1
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:
237-- main = 'runStreamT' $ (delay 1 <> delay 2) '<=>' (delay 3 <> delay 4)
240-- ThreadId 36: Delay 1
241-- ThreadId 36: Delay 3
242-- ThreadId 36: Delay 2
243-- ThreadId 36: Delay 4
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.
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:
257-- main = 'runStreamT' $ delay 3 '<|' delay 2 '<|' delay 1
260-- ThreadId 42: Delay 1
261-- ThreadId 41: Delay 2
262-- ThreadId 40: Delay 3
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 '<>'.
271-- main = 'runStreamT' $ (p 1 '<|' p 2) '<|' (p 3 '<|' p 4)
272-- where p = liftIO . print
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
294-- main = 'runStreamT' $ traced (sqrt 9) '<|' traced (sqrt 16) '<|' traced (sqrt 25)
295-- where traced m = liftIO (myThreadId >>= print) >> m
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.
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 '<|>'.
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.
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:
334-- import Network.HTTP.Simple
336-- main = 'runStreamT' $ google \<|> bing \<|> duckduckgo
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))
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".
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:
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:
371-- All of the following are equivalent:
375-- import "Streamly.Prelude"
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
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.
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.
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.
411-- When we interpret the monadic composition as 'StreamT' we get a standard
412-- list transformer like serial composition.
416-- import "Streamly.Prelude"
418-- main = 'runStreamT' $ do
419-- x <- 'each' [3,2,1]
423-- ThreadId 30: Delay 3
424-- ThreadId 30: Delay 2
425-- ThreadId 30: Delay 1
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.
433-- A console echo loop copying standard input to standard output can simply be
438-- import Data.Semigroup (cycle1)
440-- main = 'runStreamT' $ cycle1 (liftIO getLine) >>= liftIO . putStrLn
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.
450-- import "Streamly.Prelude"
452-- main = 'runStreamT' $ do
455-- liftIO $ putStrLn $ show (x, y)
464-- You will also notice that this is the monadic equivalent of the sum style
465-- composition using '<>'.
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'.
478-- import "Streamly.Prelude"
480-- main = 'runAsyncT' $ do
481-- x <- 'each' [3,2,1]
485-- ThreadId 40: Delay 1
486-- ThreadId 39: Delay 2
487-- ThreadId 38: Delay 3
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.
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.
505-- import "Streamly.Prelude"
507-- main = 'runAsyncT' $ do
510-- liftIO $ putStrLn $ show (x, y)
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
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.
531-- import "Streamly.Prelude"
533-- main = 'runInterleavedT' $ do
536-- liftIO $ putStrLn $ show (x, y)
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
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'.
557-- import "Streamly.Prelude"
559-- main = 'runParallelT' $ do
560-- x <- 'each' [3,2,1]
564-- ThreadId 40: Delay 1
565-- ThreadId 39: Delay 2
566-- ThreadId 38: Delay 3
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.
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.
581-- import "Streamly.Prelude"
584-- composed :: 'Streaming' t => t m a
589-- liftIO $ putStrLn $ show (sz, cl, sh)
593-- sizes = 'each' [1, 2, 3]
594-- colors = 'each' ["red", "green", "blue"]
595-- shapes = 'each' ["triangle", "square", "circle"]
598-- Now we can interpret this in whatever way we want:
601-- main = 'runStreamT' composed
602-- main = 'runAsyncT' composed
603-- main = 'runInterleavedT' composed
604-- main = 'runParallelT' composed
607-- Equivalently, we can also write it using the type adapter combinators, like
611-- main = 'runStreaming' $ 'serially' $ composed
612-- main = 'runStreaming' $ 'asyncly' $ composed
613-- main = 'runStreaming' $ 'interleaving' $ composed
614-- main = 'runStreaming' $ 'parallely' $ composed
617-- As an exercise try to figure out the output of this code for each mode of
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.
631-- main = ('toList' $ 'serially' $ fmap show $ 'each' [1..10]) >>= print
634-- Also see the 'mapM' and 'sequence' functions for mapping actions, in the
635-- "Streamly.Prelude" module.
639-- Applicative is precisely the same as the 'ap' operation of 'Monad'. For
640-- zipping and parallel applicatives separate types 'ZipStream' and 'ZipAsync'
643-- The following example runs all iterations serially and takes a total 17
644-- seconds (1 + 3 + 4 + 2 + 3 + 4):
648-- import "Streamly.Prelude"
649-- import Control.Concurrent
653-- d n = delay n >> return n
655-- main = ('toList' . 'serially' $ (,) \<$> s1 \<*> s2) >>= print
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)]
667-- Similalrly interleaving runs the iterations in an interleaved order but
668-- since it is serial it takes a total of 17 seconds:
671-- main = ('toList' . 'interleaving' $ (,) \<$> s1 \<*> s2) >>= print
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)]
683-- 'AsyncT' can run the iterations concurrently and therefore takes a total
684-- of 10 seconds (1 + 2 + 3 + 4):
687-- main = ('toList' . 'asyncly' $ (,) \<$> s1 \<*> s2) >>= print
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)]
699-- Similalrly 'ParallelT' as well can run the iterations concurrently and
700-- therefore takes a total of 10 seconds (1 + 2 + 3 + 4):
703-- main = ('toList' . 'parallely' $ (,) \<$> s1 \<*> s2) >>= print
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)]
715-- $compositionSummary
717-- The following table summarizes the types for monadic compositions and the
718-- operators for sum style compositions. This table captures the essence of
722-- +-----+--------------+------------+
723-- | | Serial | Concurrent |
724-- +=====+==============+============+
725-- | DFS | 'StreamT' | 'AsyncT' |
726-- | +--------------+------------+
728-- +-----+--------------+------------+
729-- | BFS | 'InterleavedT' | 'ParallelT' |
730-- | +--------------+------------+
731-- | | '<=>' | '<|>' |
732-- +-----+--------------+------------+
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.
745-- 'ZipStream' zips streams serially:
749-- import "Streamly.Prelude"
750-- import Control.Concurrent
752-- d n = delay n >> return n
753-- s1 = 'adapt' . 'serially' $ d 1 <> d 2
754-- s2 = 'adapt' . 'serially' $ d 3 <> d 4
756-- main = ('toList' . 'zipping' $ (,) \<$> s1 \<*> s2) >>= print
759-- This takes total 10 seconds to zip, which is (1 + 2 + 3 + 4) since
760-- everything runs serially:
763-- ThreadId 29: Delay 1
764-- ThreadId 29: Delay 3
765-- ThreadId 29: Delay 2
766-- ThreadId 29: Delay 4
772-- 'ZipAsync' zips streams concurrently:
776-- import "Streamly.Prelude"
777-- import Control.Concurrent
778-- import System.IO (stdout, hSetBuffering, BufferMode(LineBuffering))
780-- d n = delay n >> return n
781-- s1 = 'adapt' . 'serially' $ d 1 <> d 2
782-- s2 = 'adapt' . 'serially' $ d 3 <> d 4
785-- liftIO $ hSetBuffering stdout LineBuffering
786-- ('toList' . 'zippingAsync' $ (,) \<$> s1 \<*> s2) >>= print
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:
793-- ThreadId 32: Delay 1
794-- ThreadId 32: Delay 2
795-- ThreadId 33: Delay 3
796-- ThreadId 33: Delay 4
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.
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.
816-- import "Streamly.Prelude" (toList)
817-- import Data.List (sum)
821-- $ 'asyncly' -- Concurrent monadic processing (sqrt below)
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)
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.
835-- For more concurrent programming examples see,
836-- "Streamly.Examples.ListDirRecursive", "Streamly.Examples.MergeSortedStreams"
837-- and "Streamly.Examples.SearchEngineQuery".
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
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.
858-- {-\# LANGUAGE FlexibleContexts #-}
861-- import Control.Concurrent (threadDelay)
862-- import Control.Monad (when)
863-- import Control.Monad.State
864-- import Data.Semigroup (cycle1)
866-- data Event = Harm Int | Heal Int | Quit deriving (Show)
868-- userAction :: MonadIO m => 'StreamT' m Event
869-- userAction = cycle1 $ liftIO askUser
874-- "potion" -> return (Heal 10)
875-- "quit" -> return Quit
876-- _ -> putStrLn "What?" >> askUser
878-- acidRain :: MonadIO m => 'StreamT' m Event
879-- acidRain = cycle1 $ liftIO (threadDelay 1000000) >> return (Harm 1)
881-- game :: ('MonadAsync' m, MonadState Int m) => 'StreamT' m ()
883-- event \<- userAction \<|> acidRain
885-- Harm n -> modify $ \\h -> h - n
886-- Heal n -> modify $ \\h -> h + n
887-- Quit -> fail "quit"
890-- when (h <= 0) $ fail "You die!"
891-- liftIO $ putStrLn $ "Health = " ++ show h
894-- putStrLn "Your health is deteriorating due to acid rain,\\
895-- \\ type \\"potion\\" or \\"quit\\""
896-- _ <- runStateT ('runStreamT' game) 60
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>
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".
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
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.
927-- import "Streamly.Prelude"
928-- import System.IO (stdin)
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
935-- Interop with @pipes@:
938-- import qualified Pipes as P
939-- import qualified Pipes.Prelude as P
942-- -- streamly to pipe
943-- P.runEffect $ P.for (P.unfoldr unconsE stdinLn) (lift . putStrLn)
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
951-- Interop with @streaming@:
954-- import qualified Streaming as S
955-- import qualified Streaming.Prelude as S
958-- -- streamly to streaming
959-- S.stdoutLn $ S.unfoldr unconsE stdinLn
961-- -- streaming to streamly
962-- 'runStreamT' $ unfoldrM S.uncons S.stdinLn >>= lift . putStrLn
966-- Interop with @conduit@:
969-- import qualified Data.Conduit as C
970-- import qualified Data.Conduit.List as C
971-- import qualified Data.Conduit.Combinators as C
973-- -- streamly to conduit
974-- main = (C.unfoldM 'uncons' stdinLn) C.$$ C.print
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:
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-- +-----------------+----------------+
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
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.
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