From: Ramakrishnan Muthukrishnan Date: Sat, 27 Dec 2014 09:34:54 +0000 (+0530) Subject: hw10: exercise 2 and 3 X-Git-Url: https://git.rkrishnan.org/specifications/somewhere?a=commitdiff_plain;h=5d6f687caa769ee358732f18c6eaa06b3873cd15;p=yorgey.git hw10: exercise 2 and 3 --- diff --git a/hw10/AParser.hs b/hw10/AParser.hs index 7860c07..f506fcb 100644 --- a/hw10/AParser.hs +++ b/hw10/AParser.hs @@ -67,3 +67,32 @@ 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