Haskell Functors

Priyanka Mondal
2 min readApr 19, 2020

--

Functor is a typeclass in Haskell. Functor typeclass has only one function in it, fmap. So, datatype that is an instance of Functor typeclass and implements the fmap function is a functor. In other words, any datatype that can be mapped over can be a Functor.

data Maybe a = Nothing | Just aclass Functor f where
fmap :: (a -> b) -> f a -> f b

This says that given a function of type a -> b and type a wrapped in the context f, it will return type b wrapped in context f. Now let us implement an instance of Functor with Maybe type constructor.

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

One thing to notice here in the above example is that the type constructor in the Functor typeclass takes only one type parameter. For instance Either takes two type parameters. So It can not be a functor. Or, we can make it a functor the following way -

instance Functor (Either a) where
fmap f (Right x) = Right (f x)
fmap f (Left x) = Left x

Here instead of Either , Either a is the functor as it takes one type parameter.

If we want to make a type constructor an instance of Functor, it has to have a kind of * -> *

List is a functor too. And fmap for lists looks exactly like map function, where the context is [].

map :: (a -> b) -> [a] -> [b]
instance Functor [] where
fmap = map

Now let's talk about IO functor instance. The result of mapping something over an I/O action will be an I/O action.

instance Functor IO where
fmap f action = do
result <- action
return (f result)

return function makes an I/O action that doesn’t do anything but only presents something as its result.

Functions are functors too, and represented as (->) r

instance Functor ((->) r) where
fmap f g = f . g

As we can see its just function composition and can be defined as follows.

instance Functor ((->) r) where
fmap = (.)

fmap on a function is just function composition!

That’s all about Haskell functors !

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response