1

有没有办法创建嵌套的控制结构?例如我试过这个。但我得到了错误。

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!"  
4

2 回答 2

12

if表达式被解析为

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!"

请注意,第一个ifthen分支但没有else分支。

在 Haskell 中,每个if表达式都必须有一个then分支一个else分支。所以这是你的问题。

我赞同 bchurchill 关于使用守卫而不是嵌套if表达式的建议。

于 2013-03-06T19:44:24.463 回答
9

是的,您只需要正确缩进即可。ghc 可能也不喜欢被告知它很胖。在任何一种情况下,缩进决定了哪些分支对应于哪些语句,我可能有点搞乱了顺序:

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"

更好的方法是使用受保护的条件,例如

bmiTell bmi
  | bmi < 18.5 = "foo"
  | bmi < 25.0 = "bar"
  | bmi < 30.0 = "buzz"
于 2013-03-06T19:43:18.600 回答