Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell IF statements

Tags:

haskell

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.

like image 567
switz Avatar asked Feb 06 '11 21:02

switz


People also ask

Are there if statements in Haskell?

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.

What is a guard in Haskell?

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.

How do you do does not equal in Haskell?

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


1 Answers

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.

like image 107
Dario Avatar answered Sep 18 '22 09:09

Dario