@@ -3,43 +3,48 @@ import Data.Char
33
44newtype Parser a = P (String -> [(a , String )])
55
6+ -- | Removes the `P` dummy constructor from the `Parser` type and applies it to
7+ -- an input string.
68parse :: Parser a -> String -> [(a , String )]
79parse (P p) inp = p inp
810
11+ -- | Fails if the input string is empty, otherwise succeeds with the first
12+ -- character as the result value.
913item :: Parser Char
1014item = P $ \ inp ->
1115 case inp of
1216 [] -> []
1317 (x: xs) -> [(x, xs)]
1418
19+ -- | Applies a function to the result value of a parser if the parser succeeds,
20+ -- and propagates the failure otherwise.
1521instance Functor Parser where
16- fmap f p = P $ \ inp ->
17- case parse p inp of
18- [] -> []
19- [(v, out)] -> [(f v, out)]
20-
22+ fmap f p = P $ \ str ->
23+ case parse p str of
24+ [] -> []
25+ [(x, xs)] -> [(f x, xs)]
26+
27+ -- | The `pure` function transforms a value into a parser that always succeeds
28+ -- with this value as its result without consuming any of the input string.
29+ -- | The `<*>` function applies a parser `pf` that returns a function `f` and
30+ -- an argument `xs` to a parser `px` that returns the result of applying
31+ -- the function `fmap f px` to the argument `xs`, and only succeeds if all the
32+ -- components succeed.
2133instance Applicative Parser where
22- pure v = P $ \ inp -> [(v, inp)]
23-
24- pf <*> px = P $ \ inp ->
25- case parse pf inp of
26- [] -> []
27- [(f, out)] -> parse (fmap f px) out
34+ pure x = P $ \ str -> [(x, str)]
2835
29- three :: Parser ( Char , Char )
30- three = pure f <*> item <*> item <*> item
31- where
32- f x y z = (x, z)
36+ pf <*> px = P $ \ str ->
37+ case parse pf str of
38+ [] -> []
39+ [(f, xs)] -> parse ( fmap f px) xs
3340
41+ -- | Applies the function `f` to the result value `x` from applying the parser
42+ -- `p` to the input string `str`, which when `f x` is applied returns a parser
43+ -- which is then applied with the output string `xs`.
3444instance Monad Parser where
35- p >>= f = P $ \ inp ->
36- case parse p inp of
37- [] -> []
38- [(v, out)] -> parse (f v) out
39-
40- three' :: Parser (Char , Char )
41- three' = do
42- x <- item
43- item
44- z <- item
45- return (x, z)
45+ return = pure
46+
47+ p >>= f = P $ \ str ->
48+ case parse p str of
49+ [] -> []
50+ [(x, xs)] -> parse (f x) xs
0 commit comments