File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed
Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change 1+ import Control.Applicative
2+
3+ newtype Parser a = P (String -> [(a , String )])
4+
5+ parse :: Parser a -> String -> [(a , String )]
6+ parse (P p) inp = p inp
7+
8+ item :: Parser Char
9+ item = P $ \ inp ->
10+ case inp of
11+ [] -> []
12+ (x: xs) -> [(x, xs)]
13+
14+ instance Functor Parser where
15+ fmap f p = P $ \ str ->
16+ case parse p str of
17+ [] -> []
18+ [(x, xs)] -> [(f x, xs)]
19+
20+ instance Applicative Parser where
21+ pure x = P $ \ str -> [(x, str)]
22+
23+ pf <*> px = P $ \ str ->
24+ case parse pf str of
25+ [] -> []
26+ [(f, xs)] -> parse (fmap f px) xs
27+
28+ instance Monad Parser where
29+ return = pure
30+
31+ p >>= f = P $ \ str ->
32+ case parse p str of
33+ [] -> []
34+ [(x, xs)] -> parse (f x) xs
35+
36+ instance Alternative Parser where
37+ empty = P $ \ x -> []
38+
39+ p <|> q = P $ \ x ->
40+ case parse p x of
41+ [] -> parse q x
42+ [(v, y)] -> [(v, y)]
You can’t perform that action at this time.
0 commit comments