【问题标题】:Haskell Applicative instance clarificationHaskell Applicative 实例说明
【发布时间】:2014-11-10 10:56:51
【问题描述】:

我无法理解以下 Applicative 实例。有人可以解释一下 Applicative 做什么(在这种情况下)以及如何使用它吗?或者写得少一些混淆?谢谢!

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)

【问题讨论】:

  • Getting started with Haskell 的可能重复项
  • 您编写的代码中“混淆”了什么?很清楚。
  • @BartekBanachewicz:我不明白它是如何复制的。
  • @TomEllis 我几乎看不出在 SO 上解释 Applicative 的每一个可能实例的价值。

标签: haskell


【解决方案1】:

也许下面的等效代码可以更清楚地说明发生了什么?

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

【讨论】:

  • 确实,fmapapplyToFirst 并没有使代码比您的扩展版本更清晰,尤其是因为 fmap 用于另一个函子。
【解决方案2】:

将两个解析器与&lt;*&gt; 结合使用会为您提供新的解析器。给定一个输入字符串,新解析器运行第一个解析器,返回结果和字符串的未解析剩余部分。字符串的剩余部分被提供给第二个解析器,返回一个结果和未解析的剩余部分。然后合并两个结果。如果任一解析器失败,则结果为失败。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多