Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 465
Greg S Avatar asked Aug 20 '10 08:08

Greg S


People also ask

What is fmap Haskell?

fmap is used to apply a function of type (a -> b) to a value of type f a , where f is a functor, to produce a value of type f b . Note that for any type constructor with more than one parameter (e.g., Either ), only the last type parameter can be modified with fmap (e.g., b in `Either a b`).

What is Fmap programming?

In functional programming, a functor is a design pattern inspired by the definition from category theory, that allows for a generic type to apply a function inside without changing the structure of the generic type. This idea is encoded in Haskell using type class. class Functor f where fmap :: (a -> b) -> f a -> f b.

Is functor a typeclass?

Functor in Haskell is a typeclass that provides two methods – fmap and (<$) – for structure-preserving transformations. To implement a Functor instance for a data type, you need to provide a type-specific implementation of fmap – the function we already covered.


1 Answers

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.

like image 144
GS - Apologise to Monica Avatar answered Sep 21 '22 17:09

GS - Apologise to Monica