If expressions have the following form:
if <condition> then <trueExpr> else <falseExpr>
condition is a Boolean expression. If condition evaluates to True than the whole if expression will evaluate to the value of trueExpr otherwise it will evaluate to the value of falseExpr.
If expressions differ from their imperative counterparts in that both trueExpr and falseExpr needs to be defined and they need to be of the same type.
- Implement the following function using if expressions.
fizzBuzz :: Integer -> String
Guards can be used instead of top level if expressions.
oddOrEven :: Integer -> String
oddOrEven n
| even n = "even"
| otherwise = "odd"
In the previous example there are two guards defined. The first is even n and the second is otherwise. The function will evaluate to the body of the first guard that evaluates to true. The function call will end up in a runtime error if none of the guards match. Just start ghci and check the type of the functions if you do not know what they are.
- What is the value of otherwise?
- Rewrite fizzBuzz using guards.
- Delete the finishing otherwise guard from the fizzBuzz function and compile the source file with the -Wall flag. Try to understand the warning message.
$ ghc -Wall fizzBuzz.hs
- Call the incomplete fizzBuzz function with an integer that will not match any guards.