UP | HOME

functors (haskell)

Functors are members of the typeclass Functor

A type is an instance of Functor if it implements the fmap method:

class Functor f where
    fmap :: (a -> b) -> f a -> f b

Note that f is a higher order type, that takes a type as an argument. For example, Tree, can be an instance of functor. There are no values with type Tree, rather there are values with type Tree Int, etc. In other words, the type constructor of a functor is of kind * -> *. It needs a concrete type to be a concrete type.

What are types that are functors? They are types that can be mapped over. Some people say that they are types that are "boxes" that hold other types. For example, a List or a Tree holds concrete values and can be mapped to another List or Tree that holds concrete values.

1 Example

instance Functor Maybe where
    fmap f (Just x) = Just (f x)
    fmap f Nothing = Nothing

Note that we use Maybe instead of Maybe a where a is some concrete type. This is because fmap is looking for a type that takes one argument.

2 Sources