Haskell supports quite a few ways to take different branches in your code. Some, like the venerable if expression will look familiar. Others, like guard clauses might not. In this section, you’ll learn the basics of branching in your program. Later, here, you’ll learn about pattern matching, a powerful technique you can combine with branches to make your code incredibly expressive.
The branching structure that you’re probably most familiar with from other languages is the if expression. Like most other languages, if expressions in Haskell allow you to return one value if some predicate is true, and a different value if the predicate is false. In Haskell, if structures are expressions, meaning that you can assign a variable to the result of an if expression, and also that you must have both a true and false branch for every expression. This makes the behavior of Haskell if expressions similar to the ternary ?: operator in languages like C and JavaScript.
Let’s look at a basic example to start with, by writing a program that will print a number if it’s smaller than 10, or otherwise print an error. Let’s start by opening up an empty Main.hs file and copying the following example:
| | module Main where |
| | |
| | printSmallNumber num = |
| | if num < 10 |
| | then print num |
| | else print "the number is too big!" |
| | |
| | main = printSmallNumber 3 |
Once you’ve copied the example, test to make sure it runs:
| | user@host$ runhaskell Main.hs |
| | 3 |
You might next want to refactor your program to take advantage of the fact that if expressions always return a value. If you try to run the updated version in the example, you’ll quickly notice that the obvious solution introduces a new bug.
| | printSmallNumber num = |
| | let msg = if num < 10 |
| | then num |
| | else "the number is too big!" |
| | in print msg |
When you ran this snippet you should have gotten an error that looks like this one:
| | [1 of 1] Compiling MaybeTooBig ( MaybeTooBig.hs, interpreted ) |
| | |
| | MaybeTooBig.hs:4:22: error: |
| | • No instance for (Num [Char]) arising from the literal ‘10’ |
| | • In the second argument of ‘(<)’, namely ‘10’ |
| | In the expression: num < 10 |
| | In the expression: |
| | if num < 10 then num else "the number is too big!" |
| | | |
| | 4 | let msg = if num < 10 |
| | | ^^ |
| | Failed, no modules loaded. |
The reason you got this error is, since if expressions return a value, and values in Haskell have types, you have to make sure that both the then and else clauses of the branch return the same type. Otherwise the compiler doesn’t know what type the return value should be and it has to raise an error.
You can resolve the bug in your program by making sure both branches return a string and then try running your program again with ghci. You can use the show function from earlier in this chapter to convert your number to a string:
| | printSmallNumber num = |
| | let msg = if num < 10 |
| | then show num |
| | else "the number is too big!" |
| | in print msg |
Sometimes a single branch isn’t enough to express what we want. Although Haskell doesn’t have any special syntax for chaining together multiple if expressions, you can nest them as much as you want. Consider a function that gives a size approximation for a number:
| | sizeNumber num = |
| | if num < 3 |
| | then "that's a small number" |
| | else |
| | if num < 10 |
| | then "that's a medium sized number" |
| | else "that's a big number" |
This can get tedious and difficult to read as you add more branches. Enter guard clauses. Let’s look at an example:
| | guardSize num |
| | | num < 3 = "that's a small number" |
| | | num < 10 = "that's a medium number" |
| | | num < 100 = "that's a pretty big number" |
| | | num < 1000 = "wow, that's a giant number" |
| | | otherwise = "that's an unfathomably big number" |
As you can see from the example, this is the general syntax for using a function with guards:
| | functionName argument1 argument2 -- as many arguments as you want |
| | | predicate1 = body1 |
| | | predicate2 = body2 |
| | -- as many predicates as you want |
| | | otherwise = body3 |
In short, each guard clause starts with a vertical bar, followed by a predicate, then an equals sign and the body of the function. You’ll notice in these examples that we’ve ended our guard clauses with otherwise. This is an ordinary value that’s defined for us by the standard library to make guard clauses more readable. Its value is always True.
Predicates are evaluated from top to bottom. If we added another clause to our function that checks to see if a number is greater than zero, we could end up always hitting the first branch:
| | guardSize num |
| | | num > 0 = "that's a positive number" |
| | | num < 3 = "that's a small number" |
| | | num < 10 = "that's a medium number" |
| | | num < 100 = "that's a pretty big number" |
| | | num < 1000 = "wow, that's a giant number" |
| | | otherwise = "that's an unfathomalbly big number" |
In this version of the function, we’ll get back “that’s a positive number” for any positive number, and we’ll never end up hitting our other cases.
You can use let expressions and where clauses with guards just like with other functions. Anything that you define in a let expression will only be in scope for the particular branch where it’s defined. On the other hand, variables defined inside of a where clause will be in scope for all of the branches of your function:
| | guardSize num |
| | | num > 0 = |
| | let size = "positive" |
| | in exclaim size |
| | | num < 3 = exclaim "small" |
| | | num < 100 = exclaim "medium" |
| | | otherwise = exclaim "large" |
| | where |
| | exclaim message = "that's a " <> message <> " number!" |
In this example, the size variable is only defined inside of the first branch. We’d get an error if we tried to refer to it from any of our other branches. The exclaim function on the other hand is defined inside of a where clause, so it’s available in all of the branches of our function.
A common syntax error that you might run into, especially if you are refactoring your code to add guard clauses, comes from accidentally having an extra \= symbol between the last argument to your function and before the first predicate. Let’s look at an example:
| | invalidFunction n = |
| | | n > 5 = "bigger than five" |
| | | otherwise = "smaller than five" |
If you write a function like this into a file and try to load it into ghci you’ll see a syntax error like this:
| | Main.hs:9:3: error: parse error on input ‘|’ |
| | | |
| | 9 | | n > 5 = "bigger than five" |
| | | ^ |
| | Failed, no modules loaded. |
When you see an error like this around a function with a guard clause, it’s a good sign that you might have accidentally left a stray \= symbol around at the end of the list of arguments.
Guard clauses and if expressions are only two ways to branch in Haskell. You’ll learn about a third type of branching, case expressions, later on in this book.