And*_*een 1 haskell conditional-statements
我仍然在努力学习Haskell的语法,因为它与我之前见过的任何其他编程语言都不同.在大多数命令式编程语言中,可以创建如下的嵌套条件语句:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
但是,经过多次尝试后,我仍然没有想出Haskell中的等效语法:我尝试在Haskell中创建一个等效函数,我得到了一个语法错误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))
Run Code Online (Sandbox Code Playgroud)
我不确定这里的语法有什么问题:是否有可能在Haskell中创建嵌套条件语句,就像在其他语言中一样?
Mat*_*hid 10
正如一些人建议的那样,你可以使用图案防护更轻松地做到这一点:
thing1 x
| x <= 2 = 4
| x < 5 = 3
| x < 10 = 10
| x >= 10 = ???
main = putStr (show (thing1 6))
Run Code Online (Sandbox Code Playgroud)
那不是那么整洁吗?是不是更容易弄清楚每种情况下返回的确切内容?
更新:在我忘记之前,一个常见的习惯是这样做:
thing1 x
| x <= 2 = 4
| x < 5 = 3
| x < 10 = 10
| otherwise = 6
Run Code Online (Sandbox Code Playgroud)
这使得不经意的观察者更清楚地知道所有案例都已被覆盖.