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-functors
with thesimple
template:
stack new working-with-functors simple
- Open
src/Main.hs
in the editor. We will use this file to demonstrate the usage ofFunctors
. - After initial module definition for
Main
, import the module that includes theFunctor
type 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 * x
Functor f
is a type class that needsfmap :: (a -> b) -> f a -> f a
.Data.Functor
defines afunction <$>
synonymous tofmap
. List defines an instance forFunctor
. We will use a square function to apply over a list...