Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does fmap work for List

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 ?

like image 278
Sibi Avatar asked Apr 02 '13 21:04

Sibi


1 Answers

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.

like image 157
Tikhon Jelvis Avatar answered Sep 28 '22 05:09

Tikhon Jelvis