Haskell 中的基本函子

Ale*_*lex 2 haskell functor

我知道 Functor 类型类的定义如下:

class Functor f where  
    fmap :: (a -> b) -> f a -> f b  
Run Code Online (Sandbox Code Playgroud)

在我的课程中,它说这就是将列表制作为函子实例的方式:

instance Functor [] where  
    fmap = map  
Run Code Online (Sandbox Code Playgroud)

[] a某种同义词吗[a]

chi*_*chi 5

[] a某种同义词[a]

是的,正是如此。这两种类型之间没有区别:后者只是前者的一个漂亮的表示法。

T arg1 arg2 ...在 Haskell 中,所有类型都遵循某种类型构造函数的语法T,但其中一些类型还具有在语言中硬编码的漂亮符号,以方便人类使用。这里有一些:

a -> b   means (->) a b
[a]      means [] a
(a,b)    means (,) a b
(a,b,c)  means (,,) a b c
... ditto for other tuple types
Run Code Online (Sandbox Code Playgroud)

因此,我们可以找到一个函子实例,例如instance Functor ((->) a)fmap具有类型

(x -> y) -> ((->) a x) -> ((->) a y)
Run Code Online (Sandbox Code Playgroud)

也可以写成

(x -> y) -> (a -> x) -> (a -> y)
Run Code Online (Sandbox Code Playgroud)

fmap只是函数组合,即fmap = (.)