Browse Source

Create parser.hs

Abhinav Sarkar 4 years ago
parent
commit
b98f25cab9
1 changed files with 39 additions and 0 deletions
  1. 39
    0
      2016-04-18/parser.hs

+ 39
- 0
2016-04-18/parser.hs View File

@@ -0,0 +1,39 @@
1
+module Parser where
2
+
3
+import qualified Data.Char as Char
4
+
5
+newtype Parser i o = Parser (i -> Maybe (o, i))
6
+
7
+instance Functor (Parser i) where
8
+  fmap f (Parser p) = Parser $ \i -> fmap (\(o, i') -> (f o, i')) $ p i
9
+
10
+instance Applicative (Parser i) where
11
+  pure x = Parser $ \i -> Just (x, i)
12
+
13
+  Parser ff <*> Parser fv = Parser $ \i -> case ff i of
14
+    Just (f, i') -> case fv i' of
15
+      Just (v, i'') -> Just (f v, i'')
16
+      Nothing -> Nothing
17
+    Nothing -> Nothing
18
+
19
+charParser :: Char -> Parser String Char
20
+charParser c = Parser $ \i -> case i of
21
+  (x : xs) | x == c -> Just (c, xs)
22
+  _                 -> Nothing
23
+
24
+newtype Digit = Digit { getIntOfDigit :: Int } deriving (Show, Eq, Ord)
25
+
26
+charToDigit :: Char -> Maybe Digit
27
+charToDigit c =
28
+  if Char.isDigit c then Just $ Digit (Char.digitToInt c) else Nothing
29
+
30
+digitParser :: Parser String Digit
31
+digitParser = Parser $ \i -> case i of
32
+  (c : cs) -> fmap (\d -> (d, cs)) . charToDigit $ c
33
+  _        -> Nothing
34
+
35
+numberParser :: Parser String Int
36
+numberParser = undefined
37
+
38
+runParser :: i -> Parser i o -> Maybe o
39
+runParser i (Parser p) = fmap fst (p i)

Loading…
Cancel
Save