如何写“ a == b”? X:Y”;在Erlang中,换句话说,如何编写C风格的三元运算符? [英] How to write "a==b ? X : Y" in Erlang, in other words how to write a C-style ternary operator?
问题描述
在Erlang中是否有编写这种代码的好方法?
Is there a good way to write code like this in Erlang?
A == B ? X : Y
以下是红宝石风格的代码。这也称为三元运算符。
below is ruby-style code. This is also known as a ternary operator.
推荐答案
说明
三元运算符 _的原因? _:_
之所以存在于多种语言中,是因为它们具有两个语法类:语句和表达式。由于if-then-else构造通常属于语句类,因此当您输入表达式时,没有任何方法可以使其正常工作。因此,您添加 _吗? _:_
表达式类的运算符。
Explanation
The reason the ternary operator _ ? _ : _
exists in many languages is due to the fact that they have two syntactic classes: Statements and Expressions. Since if-then-else constructions usually belong the the statement-class, there is no way to get that working for when you are entering an expression. Hence you add the _ ? _ : _
operator to the expression class.
如另一篇文章所述,您可以使用 a == b? true:false
并只写 a == b
,但这不能解释我们可能拥有 a的一般情况== b? X:Y
用于任意表达式 X
和 Y
。另请注意,在Erlang中, a == b
始终为 false
,因此您可以说,真正要做的是用 false
替换整个表达式。
As another post states, you can take a == b ? true : false
and just write a == b
, but that does not explain the general case where we may have a == b ? X : Y
for arbitrary expressions X
and Y
. Also note that a == b
is always false
in Erlang, so you could argue that the real thing to do is to replace the whole expression with false
.
幸运的是,Erlang与大多数函数式语言一样,拥有仅一个语法类,即表达式。因此,您可以在的情况下使用X =-b的情况-> ...; Y-> ...在函数中的任何位置结束
,包括其他表达式。换句话说,三元 _? _:_
运算符在Erlang中是多余的,因为情况
已经有效。
Luckily, Erlang, as is the case for most functional languages, have one syntactic class only, expressions. Hence you can use case a == b of X -> ...; Y -> ... end
in any place in a function, other expressions included. In other words, the ternary _ ? _ : _
operator is redundant in Erlang since the case
already works.
假设我们要返回一个简单的属性列表,并且需要做一些计算
Suppose we are to return a simple proplist and we have some computation we need to do
f() ->
case a == b of
true ->
[{a, 3},
{b, <<"YE">>},
{c, 7}];
false ->
[{a, 3},
{b, <<"YE">>},
{c, "HELLO!!!"}];
end.
但是由于 case
构造是一个表达式,我们可以内联它:
But since the case
construction is an expression, we can just inline it:
f() ->
[{a, 3},
{b, <<"YE">>},
{c, case a == b of
true -> 7;
false -> "HELLO!!!"
end}].
然后用这个东西完成。
在Erlang中<.c $ c> if .. end 的构造通常不是什么你要。在这种情况下,您要检查值 a == b
,它可以产生两个输出 true
或 false
。在那种情况下, case
表达式更为直接。如果必须检查多个不同的测试并选择第一个匹配项,则最好使用 if
,而我们在这里只有一个测试。
the if .. end
construction in Erlang is usually not what you want. You want to scrutinize a value a == b
in this case and it can yield one of two outputs true
or false
. In that case the case
-expression is more direct. The if
is better used if you have to check for multiple different tests and pick the first matching, whereas we only have a single test to make here.
这篇关于如何写“ a == b”? X:Y”;在Erlang中,换句话说,如何编写C风格的三元运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!