Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell Applicative instance clarification

Tags:

haskell

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)
like image 818
yonutix Avatar asked Mar 25 '26 08:03

yonutix


1 Answers

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
like image 130
Dominique Devriese Avatar answered Mar 28 '26 03:03

Dominique Devriese



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!