在Haskell中努力分析if语句和代码布局

时间:2019-09-23 20:07:12

标签: if-statement haskell

这里的代码是胡说八道,我知道,我不想针对此问题采用其他解决方案,因为这只是为了突出我的问题而不是实际目标。这是我的代码:

example x
    if x == 2 then "Input is 2"
        else if x > 2 then if x == 3 then "Input is 3"
                else "Input is greater than 3"
            else "Dunno"
        else "Dunno"

我想要的输入->输出是:

-- input
[0, 1, 2, 3, 4] 
-- output
["Dunno", "Dunno", "Input is 2", "Input is 3", "Input is greater than 3"]

Haskell入门很困难,我发现if的格式以及其他方面比Python的直观性要差。

3 个答案:

答案 0 :(得分:5)

您可以像在Python中那样格式化它,缩进每个嵌套级别:

example x =
    if x == 2 then
        "Input is 2"
    else
        if x > 2 then
            if x == 3 then
                "Input is 3"
            else
                "Input is greater than 3"
        else
            "Dunno"
    else
        "Dunno"

到那时,很明显这没有任何意义,因为elseif多。

但是由于存在模式匹配和保护,因此您通常通常不会在Haskell中嵌套那么多if

答案 1 :(得分:4)

实际上您距离很近,刚开始时只忘记了等号(=

example x = if x == 2 then "Input is 2"
        else if x > 2 then if x == 3 then "Input is 3"
                else "Input is greater than 3"
            else "Dunno"

在Haskell中,人们并不经常使用if…then…else…。通常使用后卫或模式匹配。结合模式匹配和防护的一种更优雅的书写方式是:

example :: Int -> String
example 2 = "Input is 2"
example 3 = "Input is 3"
example x | x > 3 = "Input is greater than 3"
          | otherwise = "Dunno"

我认为这使在这里执行什么逻辑更加清楚。基本上每行都覆盖一个案例,在=的左侧,我们看到条件,在右侧,我们看到结果。

答案 2 :(得分:3)

假设我们需要保持if不变,那么我将使用此缩进

if condition
then result1
else result2

导致

example x =
    if x == 2
    then "Input is 2"
    else if x > 2
         then if x == 3
              then "Input is 3"
              else "Input is greater than 3"
         else "Dunno"

(注意:由于错误,我删除了原始代码中发现的其他else "Dunno"

或者:

example x =
    if x == 2 then
       "Input is 2"
    else if x > 2 then
       if x == 3 then
          "Input is 3"
       else
          "Input is greater than 3"
    else
       "Dunno"

也很不错,因为它避免了缩进不断增加的“阶梯效应”。这是因为我们遵循该计划

if condition1 then
   result1
else if condition2 then
   result2
else if condition3 then
   result3
...
else
   resultN

当然,对于这个特定示例,我实际上将使用防护和模式匹配。

example 2 = "Input is 2"
example 3 = "Input is 3"
example x
   | x > 2 = "Input is greater than 3"
   | otherwise = "Dunno"

(可能将x > 2调整为x > 3,这在整数上是等效的,但在这里更易读)