Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the point of map in Haskell, when there is fmap?

Tags:

haskell

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?

like image 667
Clark Gaebel Avatar asked Jul 26 '11 01:07

Clark Gaebel


People also ask

What does map in Haskell do?

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.

What is Fmap in Haskell?

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.

What does <$> mean in Haskell?

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.

What is flatMap in Haskell?

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


2 Answers

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.

like image 169
luqui Avatar answered Sep 18 '22 18:09

luqui


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-only map function, and rename fmap to map instead? Well, that’s a good question. The usual argument is that someone just learning Haskell, when using map incorrectly, would much rather see an error about lists than about Functor.

like image 22
Andrei Bozantan Avatar answered Sep 19 '22 18:09

Andrei Bozantan