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)
请注意,第一个if有then分支但没有else分支.
在Haskell中,每个if表达式都必须有一个then分支和一个else分支.这就是你的问题.
我的第二个bchurchill建议使用防护而不是嵌套if表达.
是的,你只需要妥善缩进.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)