on c94f540 help sign in
70 lines 1.7 kB history raw
1# Frequently Asked Questions
3This document provides idioms or examples to solve common programming
4problems using streamly. To start with please go through [Streamly Quick
5Overview](/docs/User/Tutorials/Introduction.md) and [`Streamly examples repository`][streamly-examples].
6This document provides additional examples.
8## Distribute and Zip Concurrently
10Say, you have an input stream, and each element of the input stream is to be
11transformed in multiple ways using monadic functions. Then you want to zip the
12results together and consume the resulting stream concurrently.
14First, distribute an item to multiple effectful consumer concurrently, for
15example:
17```haskell
18import Data.Function ((&))
19import qualified Streamly.Prelude as Stream
21f1 x =
22 Prelude.map ($ x) [return . (+ 1), return . (+ 2)]
23 & Stream.fromListM
24 & Stream.fromAhead
25 & Stream.toList
26```
28Alternatively, if you want to concurrently zip different types of outputs, you
29can use `Applicative` composition:
31```haskell
32import Data.Maybe (fromJust)
33f2 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```
43Then apply the function `f` concurrently to your input stream:
45```haskell
46g f xs =
47 Stream.fromList xs
48 & Stream.mapM f
49 & Stream.fromAhead
50 & Stream.toList
51```
53```
54>>> g f1 [1,2,3,4::Int]
55[[2,3],[3,4],[4,5],[5,6]]
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```
61## Sliding Window
63```
64>>> :{
65 Stream.fromList [1,2,3,4,5::Int]
66& Stream.scan (Array.writeLastN 2)
67& Stream.toList
68:}
69[[],[1],[1,2],[2,3],[3,4],[4,5]]
70```