Skip to content

Latest commit

 

History

History
76 lines (57 loc) · 2.36 KB

17.md

File metadata and controls

76 lines (57 loc) · 2.36 KB

Higher order functions

I have already mentioned that functions can be passed as an argument to a function or returned from a function. A function that returns a function or accepts a function as parameter is called a higher order function.

Map

Map is one of the most used higher order functions. Let's have a look at it's type and try to find out what it does.

map :: (a -> b) -> [a] -> [b]

The first parameter is a function that maps from type a to type b. The second parameter is a list that contains values of type a. The return value is a list that contains values of type b.

There is only one way to create values of type b. We need to use the function passed as the first argument to map. That function can create values of type b using values of type a as its parameter. There is only one source of values of type a, the second parameter of map. With a bit more imagination we conclude that map calls the function to all values in the first list and returns a list constructed from the result values.

Start ghci and try out the following lines:

:t map
:t show
:t map show

map show [1..10]
map (*2) [1..10]

Exercise

  • Create the list knights :: [Knight] and map the favouriteColour function over the list. (Hint: Use the types defined in lecture 7.)
  • Implement the following function:
mymap :: (a -> b) -> [a] -> [b]
  • Try out mymap on the map examples from the lecture.

Map on other things

You can think of map as a function that calls its first parameter on the content's of another value not specifically a list. You might think about these things as containers to build up an initial intuition. This notion will change as you see more examples that can not fit in this abstraction.

The idea of types that can be mapped over is expressed in the Functor typeclass. List is a functor and there are many other types implementing this interface. Every implementation specifies the fmap function.

fmap :: Functor f => (a -> b) -> f a -> f b

This is the same type as map if you replace [] with f. Let's have a look at other functors.

fmap (*2) [1..10]
fmap (*2) (Just 10)
fmap (*2) (Nothing)
fmap (*2) (Left 10)
fmap (*2) (Right 10)

We will not go deeper in the introductory course. This should be enough to start experimenting with functors.