我无法理解下面的fmap实例.有人可以解释一下fmap做什么(在这种情况下)以及如何使用它?或者写一点混淆?谢谢!
newtype Parser a = P { getParser :: String -> Maybe (a, String) }
instance Functor Parser where
fmap f (P p) = P $ \s -> fmap (applyToFirst f) $ p s
{-|
Applies a function to the first component of a pair.
-}
applyToFirst :: (a -> b) -> (a, c) -> (b, c)
applyToFirst f (x, y) = (f x, y)
Run Code Online (Sandbox Code Playgroud)
它有什么作用?
它将解析器X转换为解析器Y,其中Y执行以下操作:运行解析器X并将函数f应用于解析结果对的第一个元素.
如何使用它?
p1 :: Parser String
p1 = P (\s -> Just ("foo", "bar"))
p2 :: Parser String
p2 = fmap (\s -> s ++ s) p1
Run Code Online (Sandbox Code Playgroud)
现在(getParser p2) "whatever"等于Just ("foofoo", "bar").
它可以减少混淆吗?
它实际上没有混淆.Haskell需要时间来适应.