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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With