Erlang:从函数返回
我有一个函数,其中有一系列个案陈述。
case ... of
...
end,
case ... of
...
end,
...
。
我想当某个 case 语句中出现特定 case 条件时立即从函数返回 - 这样就不会检查下一个 case 语句,并且函数只是退出/返回 我该怎么做?
I have a function in which I have a series of individual case statements.
case ... of
...
end,
case ... of
...
end,
...
etc.
I want to return from the function immediately when a particular case condition occurs in one of the case statements - so that the next case statement is not checked, and the function just exits/returns. How do I do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我建议您进行重构,以充分利用 Erlang 及其模式匹配功能。
没有
return
运算符。另外,一个鲜为人知的事实是您可以执行以下操作:Return=case ... of
case
语句可以具有“返回”值。I would suggest you refactor to harness the full power of Erlang and its pattern matching abilities.
There isn't a
return
operator. Also, a little known fact is you can do something like:Return=case ... of
a
case
statement can have a "return" value.模式匹配是重构 case 语句的好方法 - 您可以执行类似的操作
,然后您的 case 语句简单地概括为:(
在这个人为的示例中,X 将是 Passed1、Passed2、PassedLarge 或 DefaultCase)
Pattern matching is a good way to refactor a case statement - you can do something like this
and then your case statement simply wraps up to:
(X will be either passed1, passed2, passedlarge or defaultcase in this contrived example)
Erlang 没有
return
运算符。您需要将代码重构为更小的函数。您的原始代码有两个与逗号运算符链接的 case 表达式。我认为您在要保留的第一个 case 表达式中存在一些副作用。下面,我使用一个虚构的
return
运算符:像这样的表达式可以使用小函数和与类似这样的模式匹配转换为真正的 Erlang 代码:
免责声明:自从我使用它以来已经过去了 10 年。编写了 Erlang 代码,所以我的语法可能不正确。
Erlang does not have a
return
operator. You will need to refactor your code into smaller functions.Your original code has two case expressions chained with the comma operator. I presume you have some side effects in the first case expression that you want to preserve. Below, I'm using an imaginary
return
operator:An expression like this can be converted to real Erlang code using small functions and pattern matching with something resembling this:
Disclaimer: It's been 10 years since I've written Erlang code, so my syntax may be off.
在 Erlang 中,您只需使用模式匹配来触发适当的函数。如果您有太多的子句需要涵盖和处理,我还建议稍微重构一下代码。
In Erlang you just use the pattern matching to trigger the appropriate function. If you have too many clauses to cover and deal with I would also suggest to refactor the code a little bit.
一种方法是将 case 语句级联:
另一种方法是将 case 语句分成子句:
One way is to cascade your case statements:
Another one is to separate your case statements into clauses:
使用 catch/throw
调用者说:
then write
这通常被认为是不好的编程实践 - 因为程序有多个
出口点,很难摸索
use catch/throw
The caller says:
then write
This is generally considered poor programming practice - since the program has multiple
exit points and is difficult to grock