Anderson Green
Anderson Green

Reputation: 31810

Is it possible to write nested conditional statements in Haskell?

I'm still struggling to learn the syntax of Haskell, since it's unlike any other programming language that I've seen before. In most imperative programming languages, it's possible to create nested conditional statements like this:

function thing1(x){
    if(x > 2){
       if(x < 5){
           return 3;
       }
       else if(x < 10){
           return 10;
       }
       else if(x >= 10){
           return 6;
       }
    }
    else{
        return 4;
    }

}

However, I still haven't figured out the equivalent syntax in Haskell, after several attempts: I tried creating an equivalent function in Haskell, and I got a syntax error: prog.hs:10:1: parse error on input main':

thing1 x =
    if x > 2 then
        if x < 5 then
            3
        else if x < 10 then
            10
        else if(x >= 10)
            6
    else
        4

main = do
    putStr(show(thing1 6))

I'm not sure what's wrong with the syntax here: is it even possible to create nested conditional statements in Haskell, as in other languages?

Upvotes: 1

Views: 1486

Answers (3)

md2perpe
md2perpe

Reputation: 3061

You've forgot then after if(x >= 10) and you also need an else branch. But since if(x >= 10) already is the else branch of if x < 10 you could just remove if(x >= 10) or make it into a comment:

thing1 x =
if x > 2 then
    if x < 5 then
        3
    else if x < 10 then
        10
    else
        6
else
    4

Upvotes: 3

MathematicalOrchid
MathematicalOrchid

Reputation: 62818

As a couple of people suggested, you can do this more easily with pattern guards:

thing1 x
  | x <=  2 = 4
  | x <   5 = 3
  | x <  10 = 10
  | x >= 10 = ???

main = putStr (show (thing1 6))

Isn't that so much neater? Isn't it so much easier to figure out exactly what is returned in each case?

Update: Before I forget, a common idiom is to do this:

thing1 x
  | x <=  2   = 4
  | x <   5   = 3
  | x <  10   = 10
  | otherwise = 6

This makes it clearer to the casual observer that all cases are actually covered.

Upvotes: 10

Thomas W
Thomas W

Reputation: 14164

Don't you have an incomplete (un-answered) branch in the X > 2 section?

 if x < 5 then
    3
 else if x < 10 then
    10
 // else, what answer here?

The else in Haskell is mandatory.

See: http://en.wikibooks.org/wiki/Haskell/Control_structures

Upvotes: 1

Related Questions