If statement 在Haskell中解析if语句和代码布局
这里的代码是胡说八道,我知道,我不想对这个问题有不同的解决方案,因为这只是强调我的问题,而不是实际的目标。这是我的代码:If statement 在Haskell中解析if语句和代码布局,if-statement,haskell,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 "Dun
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的格式没有那么直观。事实上,您非常接近,一开始只忘了一个等号(
=
):
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"
我认为这更清楚地说明了这里执行的逻辑。基本上每一行都包含一个案例,在
=
的左侧,我们看到条件,在右侧,我们看到结果。您可以像在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"
在这一点上,它显然没有任何意义,因为else
s比if
s更多
但是您通常不会在Haskell中嵌套那么多的
if
s,因为存在模式匹配和保护。假设我们需要保持if
s的原样,我会使用这个缩进
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
,这在整数上是等效的,但在这里可读性更好)如果s等通常是用保护编写的。@WillemVanOnsem您愿意用保护键入此代码吗?@WillemVanOnsem True,但我们可以嵌套如果s,而我们不能嵌套保护。(也就是说,如果
s通常是一种代码气味,那么它会告诉我不要只评论“谢谢”,而是非常感谢:)
example 2 = "Input is 2"
example 3 = "Input is 3"
example x
| x > 2 = "Input is greater than 3"
| otherwise = "Dunno"