Greg S
Greg S

Reputation: 12548

Haskell coding-style: map, fmap or <$>?

Is there any reason to prefer one of the following notations over the others or is this simply a matter of preference?

map toLower "FOO"

fmap toLower "FOO"

toLower <$> "FOO"

As an aside: I realize that <$> is the same as `fmap`. Am I right in the assumption that map is just a less general form of fmap?

Upvotes: 37

Views: 3952

Answers (2)

Ganesh Sittampalam
Ganesh Sittampalam

Reputation: 29110

As you say, map is a less general form of fmap. If you know you have a list then I would use map as it makes the code clearer and if you make a mistake the error message is likely to be less confusing. However to a large extent it's a matter of preference.

(<$>) is the same as fmap. Until GHC 7.10 it wasn't exported by the Prelude so wasn't available by default - but even with older GHC versions it's easy to import from Data.Functor or Control.Applicative and these days it's pretty much the standard way to do this.

Upvotes: 40

Neil Brown
Neil Brown

Reputation: 3558

I agree with Ganesh that map is clearer for lists. I use <$> over fmap, unless it is partially applied. So I'd use fmap reverse to declare a function that reverses all elements of some functor but if I have all the arguments available (e.g. if I'm writing a line in a do block) I tend to use the operator form: reverse <$> f x

Upvotes: 12

Related Questions