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
|
module Parse where
infixr 3 <|>
infixr 4 <*>, <.>, <:>
type Parser t a = [t] -> [(a,[t])]
(<|>) :: Parser t a -> Parser t a -> Parser t a
p <|> q = \ts -> p ts ++ q ts
(<*>) :: Parser t a -> (a -> Parser t b) -> Parser t b
p <*> f = \ts -> concat [ f x ts' | (x,ts') <- p ts ]
update :: (a -> b) -> Parser t a -> Parser t b
update f p = map (\ (x,ts) -> (f x,ts)) . p
(<.>) :: Parser t a -> Parser t _ -> Parser t a
p <.> q = p <*> \x -> update (const x) q
(<:>) :: Parser t _ -> Parser t a -> Parser t a
p <:> q = p <*> const q
empty :: a -> Parser t a
empty x ts = [(x,ts)]
satisfy :: (t -> Bool) -> Parser t t
satisfy _ [] = []
satisfy p (t:ts) = if p t then [(t,ts)] else []
terminal :: Eq t => t -> Parser t t
terminal s = satisfy (s==)
star :: Parser t a -> Parser t [a]
star p = empty [] <|> p <*> \x -> update (x:) (star p)
some :: Parser t a -> Parser t [a]
some p = p <*> \x -> update (x:) (star p)
|