Haskell:单个函数中的多个 Case 语句
我想在 Haskell 函数中包含多个 case 语句(请参阅下面的假设函数示例)。
然而,它不是合法的 Haskell。完成同样事情的更好方法是什么?此外,如果 case 语句不返回任何内容,而只是设置某个值,那么为什么在函数中使用多个 case 语句是不合法的?
(我会在第 5 行收到“输入‘case’时出现解析错误”)
tester x y =
case (x < 0) of
True -> "less than zero."
False -> "greater than or equal to zero."
case (y == "foo")
True -> "the name is foo."
False -> "the name is not foo."
请注意,如果我的函数只是:
tester x y =
case (x < 0) of
True -> "less than zero."
False -> "greater than or equal to zero."
...那么它将编译。
I want to include more than one case statement in a Haskell function (see below for an example of a hypothetical function).
However, it is not legal Haskell. What is a better way of accomplishing the same thing? Furthermore, if the case statements are not returning anything, but simply setting some value, why is it not legal to have more than one case statement in a function?
(I would get a "parse error on input `case'" on line 5)
tester x y =
case (x < 0) of
True -> "less than zero."
False -> "greater than or equal to zero."
case (y == "foo")
True -> "the name is foo."
False -> "the name is not foo."
Note that if my function were simply:
tester x y =
case (x < 0) of
True -> "less than zero."
False -> "greater than or equal to zero."
...then it would compile.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一般来说,函数体必须是单个表达式(通常由较小的表达式)。例如,以下内容是不允许的:
这相当于您的第一个示例 - 我们刚刚用一种表达式(字符串文字)替换了另一种表达式(您的 case 表达式)。
当然可以在 Haskell 函数中包含多个 case 表达式:
或者甚至:
这些之所以有效,是因为函数的主体是单个表达式(尽管两者都不是真正惯用的 Haskell)。
In general the body of a function has to be a single expression (very often made up of smaller expressions). The following isn't allowed, for example:
This is equivalent to your first example—we've just substituted one kind of expression (string literals) for another (your case expressions).
It's certainly possible to include more than one case expression in a Haskell function:
Or even:
These work because the body of the function is a single expression (although neither is really idiomatic Haskell).
不过,在这种情况下我不会使用 case 语句,这个 IMO 看起来更好:
I wouldn't use a case statement in this case though, this IMO looks better:
一般来说,看起来你想要的是守卫。但是,正如已经提到的,您的函数不是单个表达式。假设您想返回一个字符串元组,可以使用守卫这样编写(以及来自 Arrows 的一些添加的乐趣):
您还可以将 Control.Arrow 位全部删除并写入:
In general, it looks like what you want is guards. However, as already mentioned, your function is not a single expression. Assuming that you want to return a tuple of strings, it can be written like this using guards (and some added fun from Arrows):
You could also drop the Control.Arrow bit all together and write: