Haskell 哈斯克尔:理解函子

Haskell 哈斯克尔:理解函子,haskell,functor,Haskell,Functor,我正在做一个关于Applicative Functor的Haskell教程: 在本教程中,给出了以下解析器: -- 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

我正在做一个关于Applicative Functor的Haskell教程:

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

-- 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中,我们被要求为解析器实现一个应用程序实例。
在实现Applicative之前,我们需要实现Functor。
我的函子解析器实现是:

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
    )
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)
然而,我找到了实现这个函子的另一种方法:
函子解析器实现为:

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
    )
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’部分,你能帮我吗?
据我理解:

  • 解析器rp:“rp”可以是任何东西(整数、元组、函数……),我们不应该知道它是什么
  • “.”运算符仅适用于函数
  • 因此,我们不能将“.”和“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的评论。

这是一个函子,不是一个函子,因此您使用了错误的名称:)谢谢您,威廉。我把英语的“functor”和法语的“foncteur”混在一起了。我的错误:(
rp
是一个类型为
String->Maybe(a,String)
的函数,它是
解析器
构造函数的参数类型。该类型中只有
a
类型变量可以是任何类型。