It’s about time we considered the function part of Functional Programming if we are going to write any useful programs! The AQA specification outlines some theory about what functions are. Whilst this is not crucial for understanding how to program using Haskell, it helps us understand what we should be trying to achieve and, importantly, the key terms we should use:

– Know that a function, f, has a function type f: A → B (where the type is A → B, A is the argument type, and B is the result type).

– Know that A is called the domain and B is called the co-domain.

– Know that the domain and co-domain are always subsets of objects in some data type.

Remember that a function is the relationship between a set of inputs and their equivalent outputs. The **function type** (also known as the arrow type) *f: A → B *is used to indicate what type of data is going to be input into the function and what type will be produced. As a simple example consider a function called *squareMe *which is used to find the square of an input value. If we assume that it will only deal with whole numbers then the type can be described as

squareMe: integer → integer

The arrow in the function type is showing that a value from the set A will be mapped to a corresponding value in a second set of values B. Previously we described these as integers but this covers a very large range of values! We narrow this down to smaller subsets of the integer set called the **domain** and the **co-domain**. In our example this could be described as:

The domain A = {1,2,3} The co-domain B = {1,2,3,4,5,6,7,8,9}

Notice that our function will not necessarily map to every value in the co-domain set. We can now say that for our function of type *squareMe: A → B*, where *A* is the domain of *squareMe* and *B* the co-domain, the expression *squareMe(a) *takes the **argument** *a* and produces a **result** *squareMe(a)*:

We can implement this as a Haskell program and run it in GHCi. Rather than entering each instruction directly into the interpreter we can create a separate source file and load it into GHCi. Firstly in a notepad editor define the function type:

squareMe :: Integer -> Integer

…and on the next line define the function itself (don’t worry about the syntax for now):

squareMe a = a * a

Save the file with a hs extension, for example, *squareMe.hs* and then load it into the interpreter using commands similar to:

:cd c:\My Haskell Files :l squareMe.hs

or if you are using WinGHCi you can use the GUI to browse to the file and load:

Assuming there are no errors you should be able to call the function and get results you would expect:

Prelude> squareMe(1) 1 Prelude> squareMe(2) 4 Prelude> squareMe(3) 9

## Recent Comments