blob: 838c8bf34471d9f323ddb28376954f0832afcb36 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE ExistentialQuantification #-}
module Unfold
( Unfold (..)
, supplyFirst
, many
, lmap
)
where
import Step (Step(..))
#if defined(FUSION_PLUGIN)
import Fusion.Plugin.Types (Fuse(..))
#endif
data Unfold m a b =
-- | @Unfold step inject@
forall s. Unfold (s -> m (Step s b)) (a -> m s)
{-# INLINE [1] lmap #-}
lmap :: (a -> c) -> Unfold m c b -> Unfold m a b
lmap f (Unfold ustep uinject) = Unfold ustep (uinject Prelude.. f)
{-# INLINE [1] supplyFirst #-}
supplyFirst :: a -> Unfold m (a, b) c -> Unfold m b c
supplyFirst a = lmap (a, )
#if defined(FUSION_PLUGIN)
{-# ANN type ConcatState Fuse #-}
#endif
data ConcatState s1 s2 = ConcatOuter s1 | ConcatInner s1 s2
-- | Apply the second unfold to each output element of the first unfold and
-- flatten the output in a single stream.
--
-- /Since: 0.8.0/
--
{-# INLINE [1] many #-}
many :: Monad m => Unfold m a b -> Unfold m b c -> Unfold m a c
many (Unfold step1 inject1) (Unfold step2 inject2) = Unfold step inject
where
inject x = do
s <- inject1 x
return $ ConcatOuter s
{-# INLINE [0] step #-}
step (ConcatOuter st) = do
r <- step1 st
case r of
Yield x s -> do
innerSt <- inject2 x
return $ Skip (ConcatInner s innerSt)
Skip s -> return $ Skip (ConcatOuter s)
Stop -> return Stop
step (ConcatInner ost ist) = do
r <- step2 ist
return $ case r of
Yield x s -> Yield x (ConcatInner ost s)
Skip s -> Skip (ConcatInner ost s)
Stop -> Skip (ConcatOuter ost)
|