Erlang等于if else [英] Erlang equivalent to if else
问题描述
如果Value1 < N做某事
else if Value1> = N do something
如果Value2< N做某事
否如果Value2> = N做某事
我想要在每个执行的一个语句。
如何在erlang工作?没有别的。我使用多个守卫,但是看起来我有4个if语句。如果某些条件
代码;
$ b
如果其他条件
代码
结束。
我收到一个语法错误。
如果
的表单是:
if
< guard 1> - > < body1> ;
< guard 2> - > < body2> ;
...
end
它工作在if-clause中尝试守卫在自上而下的顺序(这被定义)直到它成功的测试,那么该子句的正文被评估,并且如果
表达式返回最后一个表达式的值在身上。因此,其他语言中的 else
如果没有任何守卫成功,则会生成 if_clause
错误。一个常见的全面防守只是 true
,它总是成功,但一切都可以是任何事情。
case
的表单是:
case< EXPR>的
< pat 1> - > < body1> ;
< pat 2> - > < body2> ;
...
end
它的工作原理是先评估然后尝试将该值与case-clause中的模式匹配,直到匹配,然后该子句的正文为
评估,并且案例
表达式返回正文中最后一个表达式的值。如果没有模式匹配,则会生成 case_clause
错误。
请注意, if
和
case
都是表达式(一切都是一个表达式),所以它们都必须返回值。这是没有默认值的原因之一,如果没有成功/匹配。也强迫你覆盖所有选项;这对于 case
尤为重要。 如果
只是 case
的退化案例,那么它继承了它。在Erlang理由中有一个的历史,您可以在trapexit.org的用户贡献下找到。
I have 2 parts of code I want to execute. Both are conditionals
if Value1 < N do something
else if Value1 >= N do something
if Value2 < N do something
else if Value2 >= N do something
I want at one statement of each to execute.
How does the if work in erlang? there is no else. I use multiple guards, but that looks like I have 4 if statements. in groups of 2.
if some condition
code;
if other condition
code
end.
I get a syntax error.
The form for an if
is:
if
<guard 1> -> <body1> ;
<guard 2> -> <body2> ;
...
end
It works trying the guards in if-clauses in top-down order (this is defined) until it reaches a test which succeeds, then the body of that clause is evaluated and the if
expression returns the value of the last expression in the body. So the else
bit in other languages is baked into it. If none of the guards succeeds then an if_clause
error is generated. A common catch-all guard is just true
which always succeeds, but a catch-all can be anything which is true.
The form for a case
is:
case <expr> of
<pat 1> -> <body1> ;
<pat 2> -> <body2> ;
...
end
It works by first evaluating and then trying to match that value with patterns in the case-clauses in op-down order (this is defined) until one matches, then the body of that clause is
evaluated and the case
expression returns the value last expression in the body. If no pattern matches then a case_clause
error is generated.
Note that if
and case
are both expressions (everything is an expression) so they both must return values. That is one reason why there is no default value if nothing succeeds/matches. Also to force you to cover all options; this is especially important for case
. if
is just a degenerate case of case
so it inherited it. There is a bit of history of if
in the Erlang Rationale which you can find on trapexit.org under user contributions.
这篇关于Erlang等于if else的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!