next up previous
Next: Types in Haskell Up: The Frightened Freshers Guide Previous: Step-by-step evaluation

Conditional statements (If-then-else)

Like a great deal of other languages, there are conditional statements that will control the flow of logic in a program. The way in which an if statement is constructed is slightly different to what you may be used to though as Haskell relies on whitespace to figure out just what is part of the if and what is not. Below is a short example of using an if statement in a haskell function.


\begin{lstlisting}
myMax :: Int->Int->Int
- Finds which one of the parameters is the highest
myMax x y =
if x >= y
then x
else y
\end{lstlisting}

Hopefully (if LaTeX or Latex2html do not eat my formatting) you can see that an if statement needs its then and else parts to be indented at least as far as the if. This also means that the function above can be re-written in a slightly shorter form:


\begin{lstlisting}
myMax :: Int->Int->Int
- Finds which one of the parameters is the highest
myMax x y =
if x >= y
then x
else y
\end{lstlisting}

This is still legal because the then and else come after the if. Haskell relies on layout to do a lot of its processing. In Java it would be common to wear out your semicolon key on your keyboard. Haskell does not enforce this on you and relies on you to set out programs neatly. You can also do slightly more interesting if statements that have more than one condition to be true.


\begin{lstlisting}
if ((x == y) && (y == z)) then x else y
\end{lstlisting}

Although that little bit of code did not really have a point to it it is worth noting the double ampersand signs to represent logical AND. If we were to feed this little bit of code with values for x y and z of 1 2 and 2 then (x==y) would evauate to False, (y==z) to True and (False) && (True) equals False. Therefore the else section of code would be exeuted and y would be the output.

It is worth noting that haskell uses lazy evaluation! If the first bit of an if statement with an && happens to turn out to be False then the second bit will be skipped over by hugs.


next up previous
Next: Types in Haskell Up: The Frightened Freshers Guide Previous: Step-by-step evaluation
Tom Carlson 2006-04-11