I have trouble in understanding the following Applicative instance. Can someone explain me what Applicative do(in this case) and how it can be used? Or write it less obfuscated? Thanks!
newtype Parser a = P { getParser :: String -> Maybe (a, String) }
instance Applicative Parser where
pure = success
P p <*> P p' = P $ \s -> case p s of
Just (f, s') -> fmap (applyToFirst f) $ p' s'
Nothing -> Nothing
{-|
Applies a function to the first component of a pair.
-}
applyToFirst :: (a -> b) -> (a, c) -> (b, c)
applyToFirst f (x, y) = (f x, y)
Maybe the following equivalent code makes it more clear what's going on?
instance Applicative Parser where
pure v = P (\s -> Just (v, s))
P p <*> P p' = P $ \s -> case p s of
Just (f, s') -> case p' s' of
Just (v, s'') -> Just (f v, s'')
Nothing -> Nothing
Nothing -> Nothing
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With