Haskell中的嵌套控件结构

mol*_*ten 1 haskell if-statement

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

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!"  
Run Code Online (Sandbox Code Playgroud)

dav*_*420 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!"
Run Code Online (Sandbox Code Playgroud)

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

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

我的第二个bchurchill建议使用防护而不是嵌套if表达.

  • 它给出了错误*,因为它缺少'else`*. (3认同)
  • @molten如果`bmi`小于18.5但不等于16.0,你想要发生什么?这基本上是缺少的'else`分支. (2认同)

bch*_*ill 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"
Run Code Online (Sandbox Code Playgroud)

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

bmiTell bmi
  | bmi < 18.5 = "foo"
  | bmi < 25.0 = "bar"
  | bmi < 30.0 = "buzz"
Run Code Online (Sandbox Code Playgroud)

  • 不要使用拥抱.使用Haskell平台:http://www.haskell.org/platform/ (2认同)