Haskell应用实例说明

Haskell Applicative instance clarification

我在理解以下适用实例时遇到麻烦。有人可以解释一下应用程序的作用(在这种情况下)以及如何使用它吗?还是写得少些混淆?谢谢!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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)


也许下面的等效代码可以使发生的事情更清楚?

1
2
3
4
5
6
7
8
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


将两个解析器与<*>组合在一起将为您提供新的解析器。给定输入字符串,新的解析器将运行第一个解析器,返回结果以及该字符串的未解析其余部分。字符串的其余部分提供给第二个解析器,返回结果和未解析的剩余部分。然后将两个结果合并。如果任一解析器失败,则结果为失败。