]> git.rkrishnan.org Git - yorgey.git/blobdiff - hw10/AParser.hs
Add functor instance of parser
[yorgey.git] / hw10 / AParser.hs
index 0ee3090a2d54cb8bfd5cc67d3be0096f0a09a27e..7860c07073ee8b71b7618ca1f73e3b40d5bb7fc6 100644 (file)
@@ -57,3 +57,13 @@ posInt = Parser f
 ------------------------------------------------------------
 -- Your code goes below here
 ------------------------------------------------------------
+
+-- Exercise 1. functor instance for Parser
+instance Functor Parser where
+    -- Parser a == String -> (a, String)
+    -- first :: (a -> b) -> (a, c) -> (b, c)
+    -- fmap :: (a -> b) -> Parser a -> Parser b
+    fmap f (Parser pf) = Parser (\s -> case (pf s) of
+                                         Nothing -> Nothing
+                                         Just v -> Just $ (uncurry (first f) v))
+        where first f' a b = (f' a, b)