5

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.

1
  • Yeah, your line of reasoning was on the right track. What would it mean to have more than one right side "executed"? There are no side effects so everything we "do" we must return. Which value would we return? Or we would have to have a way to combine them... which way would we use? (Just a few questions to guide you to Haskell philosophy) Commented Feb 6, 2011 at 22:10

4 Answers 4

9

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Note that in Haskell, the else portion of if statements is mandatory. See Haskell 2010: Conditionals. And then there's "when" and "unless"
2

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").

Comments

1

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.