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

Ret*_*sek -1 haskell if-statement

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

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

我的预期输入->输出是:

-- input
[0, 1, 2, 3, 4] 
-- output
["Dunno", "Dunno", "Input is 2", "Input is 3", "Input is greater than 3"]
Run Code Online (Sandbox Code Playgroud)

我很难开始使用Haskell,但是我发现if的格式以及其他方面比Python的直观性要差得多。

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

在这一点上,很明显,它没有任何意义,因为elses比ifs多。

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