Working with Functors
In this recipe, we will use the Functor type class to perform some easy tasks. We will see how Functor resembles a map of a list by applying it to a variety of data structures.
How to do it...
- Use Stack to create a new project
working-with-functorswith thesimpletemplate:
stack new working-with-functors simple
- Open
src/Main.hsin the editor. We will use this file to demonstrate the usage ofFunctors. - After initial module definition for
Main, import the module that includes theFunctortype class:
import Data.Functor
- Define a function to square a number. We will use it to demonstrate application of this function over several data structures:
-- Square a number
square :: Num a => a -> a
square x = x * xFunctor fis a type class that needsfmap :: (a -> b) -> f a -> f a.Data.Functordefines afunction <$>synonymous tofmap. List defines an instance forFunctor. We will use a square function to apply over a list...