]> git.rkrishnan.org Git - yorgey.git/blobdiff - hw10/AParser.hs
hw10: exercises 4 and 5
[yorgey.git] / hw10 / AParser.hs
index 7860c07073ee8b71b7618ca1f73e3b40d5bb7fc6..04eb6ad0de6bd4c7cc1ad492e2c68cfd7ff58e74 100644 (file)
@@ -67,3 +67,46 @@ instance Functor Parser where
                                          Nothing -> Nothing
                                          Just v -> Just $ (uncurry (first f) v))
         where first f' a b = (f' a, b)
+
+-- Exercise 2. Applicative instance of Parser
+instance Applicative Parser where
+    -- pure :: a -> Parser a
+    pure x = Parser (\inp -> Just (x, inp))
+    -- --  (<*>) :: Parser (a -> b) -> Parser a -> Parser b
+    -- -- Parser (a -> b) == String -> Maybe (a -> b, String)
+    -- -- Parser a == String -> Maybe (a, String)
+    -- one possible implementation.
+    (Parser pf) <*> (Parser p2) = Parser (\inp -> case (pf inp) of
+                                                    Nothing -> Nothing
+                                                    Just (f, remStr) -> case (p2 remStr) of
+                                                                          Nothing -> Nothing
+                                                                          Just (vp2, s) -> Just ((f vp2), s))
+-- Exercise 3
+abParser :: Parser (Char, Char)
+-- (,) :: a -> b -> (a,b)
+-- char 'a' :: Parser Char
+-- fmap f x :: (a -> b) -> f a -> f b
+-- fmap (,) (char 'a') :: (Char -> (b -> (Char,b))) -> Parser Char -> Parser (b -> (Char, b))
+-- so output if fmap (,) (char 'a') is of type --- Parser (b -> (Char, b))
+-- now, p <*> char 'b' :: Parser (b -> (Char, b)) -> Parser Char -> Parser (Char, Char)
+abParser = (,) <$> char 'a' <*> char 'b'
+
+abParser_ :: Parser ()
+abParser_ = (\_ _ -> ()) <$> char 'a' <*> char 'b'
+
+intPair :: Parser [Integer]
+intPair = (\x _ z -> x : z : []) <$> posInt <*> char ' ' <*> posInt
+
+-- Exercise 4
+-- class Applicative f => Alternative f where
+--     empty :: f a
+--     (<|>) :: f a -> f a -> f a
+instance Alternative Parser where
+    empty = Parser(\_ -> Nothing)
+    (Parser p1) <|> (Parser p2) = Parser (\inp -> case (p1 inp) of
+                                                    Nothing -> (p2 inp)
+                                                    Just v -> Just v)
+
+-- exercise 5: int or Uppercase
+intOrUppercase :: Parser ()
+intOrUppercase = ((\_ -> ()) <$> posInt) <|> ((\_ -> ()) <$> (satisfy isUpper))