Haskell IF statements
I'm pretty new to haskell, but if you make an if statement:
function a b c
| (a+b == 0) = True
| --etc.
| otherwise 开发者_JAVA百科= 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.
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.
What you have here is not really an if statement, but rather a guard. But you are right that the second case gets "executed" only if the previous cases (by cases here I mean the expressions between the |
and =
) did not match (evaluate to True
). otherwise
is just a synonyme to True
(that way it always "matches").
It must be like an else if.
The bottom pattern otherwise
is really just True
, so if the first match didn't win, you would always get the more specific value and the otherwise value.
Correct. Though you've used guards, the way you've expressed it is more or less identical to using an if-statement. The flow of testing the conditional to yield a result will fall through the guard you've written in the order they were listed in your guard.
(a+b == 0)
Will be checked first
etc.
Will be checked second and so forth, provided no preceding conditional is true.
otherwise
Will be checked last, provided no preceding conditional is true.
精彩评论