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