I'm trying to understand what the functors are, but so far I can't. What's the difference between these 2:
Prelude> fmap (+1) [1..9]
[2,3,4,5,6,7,8,9,10]
Prelude> map (+1) [1..9]
[2,3,4,5,6,7,8,9,10]
For lists, there is no difference, map
is just fmap
specialised to lists.
fmap
has a more general type:
fmap :: Functor f => (a -> b) -> f a -> f b
this means it can be used with any functor e.g.
fmap (+ 3) (Just 4) -- Just 7
fmap (+ 4) (+ 3) 1 -- 8. Functions are functors where fmap = (.)
fmap read getLine :: IO Int -- IO is a functor
while map has type
map :: (a -> b) -> [a] -> [b]
If you look at the source, the functor instance for lists defines fmap
as map
:
instance Functor [] where
fmap = map
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