简体   繁体   English

fmap如何为List工作

[英]How does fmap work for List

Learn you a haskell gives description about Functor typeclass. 了解一下haskell给出了Functor类型类的描述。

I can see that for list, it's implemented as follows: 我可以看到,对于列表,它的实现如下:

instance Functor [] where  
fmap = map  

But how does this work ? 但这是如何工作的?

In the typeclass Functor, fmap doesn't even have an implementation. 在类型类Functor中,fmap甚至没有实现。 All it has is just type declaration like this: 所有它只是这样的类型声明:

class Functor f where  
fmap :: (a -> b) -> f a -> f b  

Just by having the type declaration, how does Haskell figure out map operation for Lists correctly ? 只是通过类型声明,Haskell如何正确地找出列表的映射操作?

map is just a normal function with type (a -> b) -> [a] -> [b] . map只是一个普通函数,类型为(a -> b) -> [a] -> [b] Unlike fmap , it is not part of the Functor typeclass. fmap不同,它不是 Functor类型类的一部分。 It works exactly how you think it does. 它完全符合您的想法。

The idea behind typeclasses is that you use the types to figure out which implementation to use. 类型类背后的想法是您使用类型来确定要使用的实现。 When we say instance Functor [] where ... , we're telling the compiler what the implementation of fmap for [] (the list type) is. 当我们说instance Functor [] where ... ,我们告诉编译器[] (列表类型)的fmap实现是什么。

In this case, the implementation for fmap is just map , which is a normal function. 在这种情况下, fmap的实现只是map ,这是一个普通的函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM