Haskell : 了解 Functor

Haskell : understand Functor

我正在做一个关于 Applicative Functor 的 Haskell 教程: CIS194: Homework10 - applicative

在教程中,给出了以下解析器:

-- A parser for a value of type a is a function which takes a String
-- representing the input to be parsed, and succeeds or fails; if it
-- succeeds, it returns the parsed value along with the remainder of
-- the input.
newtype Parser a = Parser { runParser :: String -> Maybe (a, String) }

在练习 2 中,我们被要求为 Parser 实现一个 Applicative 实例。
在实现Applicative之前,我们需要先实现Functor。
我的 Functor Parser 实现是:

instance Functor Parser where
  fmap f p = Parser ( -- take a function and a parser
    \s0 -> case runParser p s0 of -- parse a string
        Nothing -> Nothing -- if parse fails, returns nothing
        Just (a,s1) -> Just (f a,s1) -- if parse succeed, returns
                                      --1. 1st function applied to parsed result
                                      --2. remaining string
    )

但是我找到了另一种实现这个 Functor 的方法: bschwb /cis194-solutions
Functor Parser 实现是:

first :: (a -> b) -> (a, c) -> (b, c)
first f (a, c) = (f a, c)

instance Functor Parser where
  fmap f (Parser rp) = Parser (fmap (first f) . rp)

我不明白'. rp'部分,你能帮帮我吗?
据我了解:

感谢您的帮助。

newtype Parser a = Parser { runParser :: String -> Maybe (a, String) }中,我关注的是数据类型Parser a,而不是构造函数Parser :: (String -> Maybe (a, String)) -> Parser a

现在很清楚了:

instance Functor Parser where
    fmap -- Functor f => (a->b) -> f a -> f b
      func -- a -> b
      (Parser rp) -- regarding Parser constructor rp :: String -> Maybe (a, String)
     = Parser
      (
        fmap (first func) -- we can deduce : fmap (first func) :: Functor f => f (a, c) -> f (func a, c)
        . -- and we know : (.) :: (b -> c) -> (a -> b) -> (a -> c)
        rp -- rp :: String -> Maybe (a, String)
      ) -- therefore : fmap (first func).rp :: String -> Maybe (func a, String)

感谢 duplode 的评论。