on master help sign in
Add a FAQ for common example snippets
commit49638b84c893fedb08e8efbd8691537538ce2e7f authorHarendra Kumar <harendra@composewell.com> dateWed 15 Sep 2021, 15:05 (5 years ago) parent1bcdfdb
1 file changed+59
docs/faq.md+59
docs/faq.mdnew file+59
@@ -0,0 +1,59 @@
1+# Frequently Asked Questions
2+
3+This document provides idioms or examples to solve common programming
4+problems using streamly. To start with please go through [Streamly Quick
5+Overview](README.md) and [`Streamly examples repository`][streamly-examples].
6+This document provides additional examples.
7+
8+## Distribute and Zip Concurrently
9+
10+Say, you have an input stream, and each element of the input stream is to be
11+transformed in multiple ways using monadic functions. Then you want to zip the
12+results together and consume the resulting stream concurrently.
13+
14+First, distribute an item to multiple effectful consumer concurrently, for
15+example:
16+
17+```haskell
18+import Data.Function ((&))
19+import qualified Streamly.Prelude as Stream
20+
21+f1 x =
22+ Prelude.map ($ x) [return . (+ 1), return . (+ 2)]
23+ & Stream.fromListM
24+ & Stream.fromAhead
25+ & Stream.toList
26+```
27+
28+Alternatively, if you want to concurrently zip different types of outputs, you
29+can use `Applicative` composition:
30+
31+```haskell
32+import Data.Maybe (fromJust)
33+f2 x =
34+ (,,)
35+ <$> Stream.fromEffect (return $ show x)
36+ <*> Stream.fromEffect (return $ x + 1)
37+ <*> Stream.fromEffect (return $ fromIntegral x / 2)
38+ & Stream.fromAsync
39+ & Stream.head
40+ & fmap fromJust
41+```
42+
43+Then apply the function `f` concurrently to your input stream:
44+
45+```haskell
46+g f xs =
47+ Stream.fromList xs
48+ & Stream.mapM f
49+ & Stream.fromAhead
50+ & Stream.toList
51+```
52+
53+```
54+>>> g f1 [1,2,3,4::Int]
55+[[2,3],[3,4],[4,5],[5,6]]
56+
57+>>> g f2 [1,2,3,4::Int]
58+[("1",2,0.5),("2",3,1.0),("3",4,1.5),("4",5,2.0)]
59+```