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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
|
module NDState where
infixl 1 >+, >!, >+=
infixl 3 <|>
infixl 4 <$>, <*>
data Result a
= Return a
| Choice (Result a) (Result a)
bindResult :: Result a -> (a -> Result b) -> Result b
bindResult (Return x) f = f x
bindResult (Choice a b) f = Choice (bindResult a f) (bindResult b f)
type State s a = s -> Result (a, s)
runState :: State s a -> s -> Result (a, s)
runState state s = state s
(>+=) :: State s a -> (a -> State s b) -> State s b
(m >+= f) s = bindResult (runState m s) (\(x, s') -> runState (f x) s')
(>+) :: State s a -> State s b -> State s b
m >+ n = m >+= \_ -> n
(>!) :: State s () -> State s b -> State s b
m >! n = m >+= \() -> n
returnS :: a -> State s a
returnS x s = Return (x, s)
choiceS :: State s a -> State s a -> State s a
choiceS a b s = Choice (runState a s) (runState b s)
getS :: State s s
getS = getsS id
getsS :: (s -> t) -> State s t
getsS f s = Return (f s, s)
putS :: s -> State s ()
putS s _ = Return ((), s)
modifyS :: (s -> s) -> State s ()
modifyS f s = Return ((), f s)
sequenceS :: [State s a] -> State s [a]
sequenceS =
foldr (\s newS -> s >+= \a ->
newS >+= \as ->
returnS (a:as))
(returnS [])
sequenceS_ :: [State s a] -> State s ()
sequenceS_ = foldr (>+) (returnS ())
mapS :: (a -> State s b) -> [a] -> State s [b]
mapS f = sequenceS . map f
mapS_ :: (a -> State s b) -> [a] -> State s ()
mapS_ f = sequenceS_ . map f
(<$>) :: (a -> b) -> State s a -> State s b
(<$>) f act = act >+= \x -> returnS (f x)
(<*>) :: State s (a -> b) -> State s a -> State s b
a <*> b = a >+= \f -> b >+= \x -> returnS (f x)
(<|>) :: State s a -> State s a -> State s a
(<|>) = choiceS
anyS :: (a -> State s Bool) -> [a] -> State s Bool
anyS p xs = or <$> mapS p xs
allS :: (a -> State s Bool) -> [a] -> State s Bool
allS p xs = and <$> mapS p xs
|