Skip to main content

functor typeclass

definition

class Functor f where
map :: forall a b. (a -> b) -> f a -> f b
warning

In the definitions of typeclasses we learned so far, the type variable that played the role of the type in the typeclass was a concrete type, like the a in (= =) :: (Eq a) = > a -> a -> Bool. But now, the f is not a concrete type, but a type constructor that takes one type parameter.

📌 Functor wants a type constructor that takes one type and not a concrete type.

functor analogy: box computational context

functor examples

IO

(r->)

We usually mark functions that take anything and return anything as a -> b.

Mapping one function over a function has to produce a function, just like mapping a function over a Maybe has to produce a Maybe and mapping a function over a list has to produce a list.

Lifting a function:

(a -> b) -> (f a -> f b)

Intuitation on functor

If you think of functors as things that output values, you can think of mapping over functors as attaching a transformation to the output of the functor that changes the value.

Another example is mapping over functions. When we do fmap (+ 3) (_ 3), we attach the transformation (+ 3) to the eventual output of (_ 3). Looking at it this way gives us some intuition as to why using fmap on functions is just composition (fmap (+ 3) (_ 3) equals (+ 3) . (_ 3), which equals \x -> (( x* 3) + 3)), because we take a function like (* 3) then we attach the transformation (+ 3) to its output. The result is still a function,