Functors
The first constructor type class we will encounter in this chapter is perhaps the simplest of all: Functor
. This type class generalizes the higher-order map :: (a -> b) -> ([a] -> [
b])
.
Recall the definition of map
:
Prelude
map :: (a -> b) -> ([a] -> [b])
map f [] = []
map f (x:xs) = f x : map f xs
The second pair of parentheses in the type signature of map
can be dropped without changing the meaning. Nevertheless, I like to add them to emphasize that map
lifts a function, (a -> b)
, on elements to a function, ([a] -> [b])
, on lists.
The idea is that map
transforms the elements of the list without changing the structure of the list itself:
*Main> map show [1,2,3,4] ["1","2","3","4"]
The Functor
type class generalizes this idea from lists to other type constructors of the * -> *
kind:
Prelude
class Functor f where
fmap :: (a -> b) -> (f a -> f b)
(<$...