Lesson 27. The Functor type class
After reading lesson 27, you’ll be able to
- Use the Functor type class
- Solve problems with fmap and <$>
- Understand kinds for Functors
So far in this book, you’ve seen quite a few parameterized types (types that take another type as an argument). You’ve looked at types that represent containers, such as List and Map. You’ve also seen parameterized types that represent a context, such as Maybe for missing values and IO for values that come from the complex world of I/O. In this lesson, you’ll explore the powerful Functor type class. The Functor type class provides a generic interface for applying functions to values in a container or context. To get a sense of this, suppose you have the following types:
- [Int]
- Map String Int
- Maybe Int
- IO Int
These are four different types, but they’re all parameterized by the same type: Int (Map is a special case, but the values are type Int). Now suppose you have a function with the following type signature:
This is a function that takes an Int and returns a String. In most programming languages, you’d need to write a custom version for your Int -> String function for each of these parameterized types. Because of the Functor type class, you have a uniform way to apply your single function to all these cases.