The Functor class in Haskell, what is it?

In fact, lists are functors themselves, and the function map is fmap that works only on lists!Here’s an example showing that fmap and map have the same behaviour when applied on lists:an example using fmap and mapBut how can we force a type to have this behaviour?The answer is that the type must be an instance of the Functor type class.

To better understand, let’s take a look at how this is made with the type list:how the type list is an instance of FunctorThis syntax might not be so clear for you (don’t worry, this is not the point), but I just would like to show that this instance is made on the type list itself, and not to a list of a particular type.

In fact, the type list is, by definition, a parametrized type.

This means that it is a type that takes another type to produce other types, such as list of Int, list of String, list of lists of String, and so on.

And this is the real point.

The Functor type class can’t be instantiated by every type, but just by those that takes one type parameter.

Like list, there are many other types that have this feature, and that, by consequence, can be an instance of Functor.

For example, the Tree type, that I’m going to explain better in the next paragraph.

The Tree type is either an empty tree or a node-root with two node-sons.

As said before, this type takes a one type parameter, so it can be used to create, for example, a Tree of Int, or a Tree of Char; and it is also an instance of Functor, as you can see below:how the type Tree is an instance of FunctorThis means that it is possible to use the function fmap to map over a Tree, applying a function on a node and on their left son and right son, and so on recursively, which can be very useful and easy.

In conclusionThe Functor is a type class that can be instantiated by type constructors for making them to be mapped over.

It is a really powerful tool in functional programming and it can be seen as a high-level concept of implementing polymorphism.

BibliographyMaking Our Own Types and TypeclassesIn the previous chapters, we covered some existing Haskell types and typeclasses.

In this chapter, we'll learn how to…learnyouahaskell.

comFunctors, Applicative Functors and MonoidsHaskell's combination of purity, higher order functions, parameterized algebraic data types, and typeclasses allows us…learnyouahaskell.

comHaskell FunctorHaskell Functor – Learn Haskell in simple and easy steps starting from basic to advanced concepts with examples…www.



. More details

Leave a Reply