liveBook · Manning

Functor

As explained in Learn Haskell by Example

Functor is the Haskell type class for types whose parameterized values support structure-preserving mapping over their contents.

A Functor is a Haskell type class for parameterized types whose contained value can be transformed with fmap. Its core type, fmap :: Functor f => (a -> b) -> f a -> f b, applies a function while retaining the surrounding structure. section 8.2.3

Lists, Maybe, Either, tuples, IO actions, and parsers can all preserve their own context while their inner result changes. Int cannot be a Functor because it is a concrete type rather than a type accepting a parameter. section 8.2.3 section 8.4

Map a successful CSV result

CSV parsing returns Either String Csv. Using <$> maps unsafeMkCsv over a successful result from parseColumns, while an error remains a Left. The infix operator <$> is fmap. section 8.2.2 section 8.5

Map inside IO

getArgs returns IO [String]. Writing map T.pack <$> getArgs transforms the argument strings to Text without first extracting the list from IO; the result remains IO [Text]. section 8.4

Listing 12.5 A functor instance for parsers
instance Functor Parser where
  fmap f p = Parser $ \t -> fmap (fmap f) (runParser p t)     #1

A Parser Functor maps a conversion over the successful parsed value nested inside Either and a result tuple, preserving input remainder and parse failures. section 12.1.2

Functor instances also make parsers more precise. A parser for the text "P1" can become a Parser MagicNumber by mapping const P1; <$ is shorthand when every successful result should become one constant value. section 12.1.2

For a custom RandomIO generator, a Functor instance would provide the equivalent of map: transform generated values while leaving generation in the RandomIO context. section 9.1.6

How Learn Haskell by Example covers it

How deep it goes
Defines Functor through fmap and kinds, then implements a Parser instance; functor laws are not detailed.
Examples
Demonstrates CSV Either mapping, command-line IO [String] conversion, Parser MagicNumber construction, and a RandomIO Functor exercise.
What it assumes
Introduces parameterized types and kinds while relating fmap to familiar list map and previously encountered Maybe mapping.
What you can do after
Apply it via fmap, <$> and <$ to change contained results while preserving list, Maybe, Either, IO, or Parser structure.
How it connects
Connects Functor to fmap, <$> , <$, kinds, Either, Maybe, IO, parsers, applicatives, and monads.

Also explained in

Compare how 6 books explain functor →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Haskell by Example. The section links point to the parts of the book it draws on.