I'm pretty new to haskell, but if you make an if statement:
function a b c
| (a+b == 0) = True
| --etc.
| otherwise = False
Is the second if statement the same as an else if in other languages, or is it just another if. I assume its the former as you can only have one output, but I just want to make sure.
In Haskell, multiple lines of if will be used by separating each of the if statement with its corresponding else statement. In the above example, we have introduced multiple conditions in one function. Depending on the function inputs, it will provide us different outputs.
A guard is basically a boolean expression. If it evaluates to True, then the corresponding function body is used. If it evaluates to False, checking drops through to the next guard and so on. If we call this function with 24.3, it will first check if that's smaller than or equal to 18.5.
The == operator means "is equal". The /= operator means "is not equal". It's supposed to be reminiscent of the mathematical "≠" symbol (i.e., an equals sign with a diagonal line through it).
The construct you used is called a guard. Haskell checks the given alternatives one after another until one condition yields True
. It then evaluates the right hand side of that equation.
You could pretty well write
function n
| n == 1 = ...
| n == 2 = ...
| n >= 3 = ...
thus the guard kinds of represents an if/elseif construct from other languages. As otherwise
is simply defined as True
, the last
| otherwise =
will always be true and therefore represents a catch-all else
clause.
Nontheless, Haskell has a usual a = if foo then 23 else 42
statement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With