molten
molten

Reputation: 53

Nested control structure in Haskell

Is there any way to create nested control structure? For example I tried this. But I got error.

bmiTell :: (RealFloat a) => a -> String  

bmiTell bmi  = if bmi <= 18.5  then if bmi==16.0 then "asdasdasdsad"
           else if bmi <= 25.0 then "You're supposedly normal. Pffft, I bet  you're ugly!"  
           else if bmi <= 30.0 then "You're fat! Lose some weight, fatty!"  
           else    "You're a whale, congratulations!"  

Upvotes: 1

Views: 12230

Answers (2)

bchurchill
bchurchill

Reputation: 1420

Yeah, you just need to indent things properly. ghc probably doesn't like being told it's fat either. In either case, the indenting determines what branches correspond to what statements, and I might have messed up the order a bit:

bmiTell bmi  = if bmi <= 18.5  
               then if bmi==16.0 
                    then "asdasdasdsad"
                    else if bmi <= 25.0 
                         then "You're supposedly normal. Pffft, I bet  you're ugly!"  
                         else if bmi <= 30.0 
                              then "You're fat! Lose some weight, fatty!"  
                              else    "You're a whale, congratulations!"  
               else "foobar"

The better way to do this is with a guarded conditional, e.g.

bmiTell bmi
  | bmi < 18.5 = "foo"
  | bmi < 25.0 = "bar"
  | bmi < 30.0 = "buzz"

Upvotes: 9

dave4420
dave4420

Reputation: 47072

The if expression is parsed as

if bmi <= 18.5   -- no else!
  then if bmi==16.0
         then "asdasdasdsad"
         else if bmi <= 25.0
                then "You're supposedly normal. Pffft, I bet  you're ugly!"  
                else if bmi <= 30.0
                       then "You're fat! Lose some weight, fatty!"  
                       else "You're a whale, congratulations!"

Note that the first if has a then branch but no else branch.

In Haskell, every if expression must have a then branch and an else branch. So that's your problem.

I second bchurchill's suggestion of using guards rather than nested if expressions.

Upvotes: 12

Related Questions