(1)
The difference between Haskell’s if statement and if statements in imperative languages is that the else part is mandatory in Haskell.
在Haskell
中,if
语句的else
部分是必须有的:
doubleSmallNumber x = if x > 100
then x
else X * 2
否则会有以下编译错误:
parse error in if statement: missing required else clause
(2)
Another thing about the if statement in Haskell is that it is an expression. An expression is basically a piece of code that returns a value. 5 is an expression because it returns 5, 4 + 8 is an expression, x + y is an expression because it returns the sum of x and y. Because the else is mandatory, an if statement will always return something and that’s why it’s an expression.