简体   繁体   English

Haskell应用实例澄清

[英]Haskell Applicative instance clarification

I have trouble in understanding the following Applicative instance. 我无法理解以下Applicative实例。 Can someone explain me what Applicative do(in this case) and how it can be used? 有人能解释一下Applicative做什么(在这种情况下)以及如何使用它? 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

Combining two parsers with <*> gives you new parser. 将两个解析器与<*>组合在一起可以获得新的解析器。 Given an input string, the new parser runs the first parser returning a result and the unparsed remainder of the string. 给定一个输入字符串,新的解析器运行第一个解析器返回结果和未解析的字符串剩余部分。 The remainder of the string is given to the second parser returning a result and unparsed remainder. 字符串的其余部分将提供给第二个解析器,返回结果和未解析的余数。 Then the two results are combined. 然后结合两个结果。 If either parser fails the result is failure. 如果任一解析器失败,则结果失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM