Higher-order functions

Edmund and Tina want to become more environmentally sustainable. They have employed the use of higher-order functions to help them become green warriors of the Earth. They want to go as far as to put the local garbage collector out of a job (or at least send him a message).

TINA DOESN'T HAVE ACCESS

Type signatures warm up

These 7 R’s will help Edmund and Tina towards their quest to reduce their carbon footprints, but first they need to know what they mean.

What do the following type signatures mean? Debate in your groups.


refuse :: (a -> Bool) -> [a] -> [a]

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

reuse :: (a -> a) -> a -> [a]

repair :: (a -> b -> c) -> [a] -> [b] -> [c]

regift :: (a -> b) -> a -> b

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

recover :: (a -> b) -> (b -> c) -> (a -> c)

x:xs marks the spot

recycle is a higher order function that takes a function as input, a list as input, and returns a new list where each element of the list has that function applied to it. It is properly known in Haskell as map. All higher-order functions can be defined using recursion.

map :: (a -> b) -> [a] -> [b]
map _ [] = []
map f x:xs = ...

Have a go at defining the remainder of map. The base case is already completed for you.

More interesting higher-order functions

Edmund and Tina only need to contribute small steps towards their goal, can you help them? They are having trouble how to implement some of these vital steps.

refuse is a function that takes a predicate and a list and returns a new list where only elements that satisfy the predicate are included in that list.

  • Have a go at writing the refuse function. The type signature was given above.
  • Why is it useful? What could be a better name for refuse?

If you are having trouble thinking what a predicate could be, think about the difference between the types of > and > 3

repair is a function that takes a function and two lists, uses the function to combine the elements of the lists up to the length of the shortest list.

  • Have a go at writing the repair function. The type signature was given above.
  • Why is it useful? What could be a better name for repair?

recover is a function that takes two functions and combines them into a single function.

  • Have a go at writing the recover function. Type signature was given as usual.
  • Why is it useful? What could be a better name for recover?

reduce is a function that takes an operator, an accumulator and a list, and returns the value that the list elements were accumulated on depending on the operator.

  • Have a go at writing the reduce function. Type signature was given as usual.
  • Why is it useful? What could be a better name for reduce?