Skip to content

Commit a023af8

Browse files
committed
Add example using Alternative type class
1 parent 82686c1 commit a023af8

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
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)]

0 commit comments

Comments
 (0)