Everywhere I've tried using map
, fmap
has worked as well. Why did the creators of Haskell feel the need for a map
function? Couldn't it just be what is currently known as fmap
and fmap
could be removed from the language?
map is a function that takes two parameters: a function and a list of elements. The type signature of map is (a -> b) -> [a] -> [b] . The (a -> b) part is the function you pass to map , we will call it f . f takes one value and returns another that may be of a different type.
You can think of fmap as either a function that takes a function and a functor and then maps that function over the functor, or you can think of it as a function that takes a function and lifts that function so that it operates on functors. Both views are correct and in Haskell, equivalent.
It's merely an infix synonym for fmap , so you can write e.g. Prelude> (*2) <$> [1.. 3] [2,4,6] Prelude> show <$> Just 11 Just "11" Like most infix functions, it is not built-in syntax, just a function definition. But functors are such a fundamental tool that <$> is found pretty much everywhere.
It should be clear that flatMap is map first and then flat, you flatten the output of the map, as opposed to flattening the input list you are about to process (this isn't flatMap , this has no name, it is just a flat and then map).
I would like to make an answer to draw attention to augustss's comment:
That's not actually how it happens. What happened was that the type of map was generalized to cover Functor in Haskell 1.3. I.e., in Haskell 1.3 fmap was called map. This change was then reverted in Haskell 1.4 and fmap was introduced. The reason for this change was pedagogical; when teaching Haskell to beginners the very general type of map made error messages more difficult to understand. In my opinion this wasn't the right way to solve the problem.
Haskell 98 is seen as a step backwards by some Haskellers (including me), previous versions having defined a more abstract and consistent library. Oh well.
Quoting from the Functor
documentation at https://wiki.haskell.org/Typeclassopedia#Functor
You might ask why we need a separate
map
function. Why not just do away with the current list-onlymap
function, and renamefmap
tomap
instead? Well, that’s a good question. The usual argument is that someone just learning Haskell, when usingmap
incorrectly, would much rather see an error about lists than aboutFunctor
.
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