Haskell Application Clarification
I am having trouble understanding the following applicative instance. Can someone explain to me what the Applicator does (in this case) and how can it be used? Or write it less confusing? Thank!
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)
+3
yonutix
source
to share
2 answers
Perhaps the following equivalent code makes it clearer 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
+4
Dominique Devriese
source
to share
Combining the two parsers with <*>
gives you a new parser. Given the input string, the new parser runs the first parser that returns a result and the unopened remainder of the string. The rest of the string is assigned to the second parser, returning the result and the unopened remainder. Then the two results are combined. If any parser fails, the result is a failure.
+1
Tom ellis
source
to share