Sunday, October 01, 2006

Higher Order Functions

The last few years I have been spending my spare time with languages like Scheme, Ruby, Haskell and Erlang. The reason I’m doing this is that the expressiveness of these languages is a lot higher than that of my work language, Java. I’m able to do more with less code. And the reason for this is higher order functions. Higher order functions is enabled by having functions as first class citizens of the language.

Map

The first of the higher order funtions is map. Map takes two arguments a function and a list and returns a new list with the result of applying the funtion to every element of the list. Map raises the abstraction of list iteration by allowing me to focus on converting one element of this into one element of that instead of worrying about how to convert a list of this into a list of that. It simplifies my job.

Compose

We now have the ability to transform lists by mapping a function to every element or by filtering the elements according to some predicate function. We are also able to reduce a list by combining the elements with a binary function. We would also like the ability to create new functions by combining two functions and this is where compose comes in:

It is important that the type signatures of the functions set to compose match as can be seen in the type definition of the Haskell example above. The type returned by function g must be the input of function f.

Currying

Another method of creating new methods is currying1. Currying means creating new functions by only suppling part of the required arguments to the function. Instead of failing a new function is created. This is directly supported in Haskell, but must be done explicitly in Scheme (or by use of macros).