next up previous
Next: Importing other modules Up: The Frightened Freshers Guide Previous: What is a function?

Doing something with our function

Taking the example of doubleNumber above, we can extend it so that it actually does something. The function addTwoNumbers will take two integers and add them together, returning the result. Addition in Haskell is (Thankfully) the same as in Java, just using the + sign between two parameters. The best way to see this is in an example.

language=Haskell
\begin{lstlisting}
addTwoNumbers :: Int->Int->Int
- This function takes two numbers and adds them together
addTwoNumbers a b = a + b
\end{lstlisting}

The section below the function declaration is a comment. Code should always include comments! Without comments, if you come back to a function at some time later, then you may find that you need to re-read the code to figure out what it actually does. The third line in this little section of code is important. Firstly, we have the function name repeated and then the letters a and b. These letters are the inputs from the function and without them you will get an ugly looking error message. This is what happens when you try and remove b from the example above. Note that the function is completely useless!


\begin{lstlisting}
addTwoNumbers :: Int->Int->Int
- This function takes two numbers and adds them together
addTwoNumbers a = a
\end{lstlisting}


\begin{lstlisting}
Hugs.Base> :l t.hs
ERROR ''t.hs'':3 - Type error in explicitl...
...rs
*** Type : Int -> Int
*** Does not match : Int -> Int -> Int
\end{lstlisting}

This is one of the few error messages in Haskell that I think is useful. It is telling me that in the function addTwoNumbers it was expecting to find Int Int Int, but instead it found Int Int. This shows that you need to add b back in because when you define a function that wants two inputs and an output you do need to use all the inputs!

Once that is fixed, you can load it up into hugs (If you do not know how to load hugs and do stuff with it, see the section at the end of the document...) and type in "addTwoNumbers 1 2" and Hugs will come back with an answer of Three.

Note that you do not need to have brackets and commas around your arguments for a function, just using whitespace to break up the function name and its parameters is good enough for Haskell.


next up previous
Next: Importing other modules Up: The Frightened Freshers Guide Previous: What is a function?
Tom Carlson 2006-04-11