5
votes

Learn you a haskell gives description about Functor typeclass.

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. 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 ?

1
You might want to read the Functors tutorial I wrote as an answer to this question.AndrewC

1 Answers

17
votes

map is just a normal function with type (a -> b) -> [a] -> [b]. Unlike fmap, it is not part of the Functor typeclass. 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.

In this case, the implementation for fmap is just map, which is a normal function.