是否可以在Haskell中编写嵌套的条件语句?

时间:2013-08-03 06:13:33

标签: 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;
    }

}

但是,经过多次尝试后,我仍然没有想出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))

我不确定这里的语法有什么问题:是否有可能在Haskell中创建嵌套条件语句,就像在其他语言中一样?

3 个答案:

答案 0 :(得分:10)

正如一些人建议的那样,你可以通过模式保护更容易地做到这一点:

thing1 x
  | x <=  2 = 4
  | x <   5 = 3
  | x <  10 = 10
  | x >= 10 = ???

main = putStr (show (thing1 6))

那不是那么整洁吗?是不是更容易弄清楚每种情况下返回的确切内容?

更新:在我忘记之前,一个常见的习惯是这样做:

thing1 x
  | x <=  2   = 4
  | x <   5   = 3
  | x <  10   = 10
  | otherwise = 6

这使得不经意的观察者更清楚地知道所有案件都已被覆盖。

答案 1 :(得分:3)

您在then之后忘记了if(x >= 10),并且您还需要一个else分支。但由于if(x >= 10)已经是else的{​​{1}}分支,您可以删除if x < 10或将其作为评论:

if(x >= 10)

答案 2 :(得分:1)

X&gt;中是否有不完整(未回答)的分支? 2节?

 if x < 5 then
    3
 else if x < 10 then
    10
 // else, what answer here?

Haskell中的else是强制性的。

请参阅:http://en.wikibooks.org/wiki/Haskell/Control_structures

相关问题