朱莉娅有三元条件运算符吗? [英] Does Julia have a ternary conditional operator?

查看:70
本文介绍了朱莉娅有三元条件运算符吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python,Java和Scala具有三元运算符.朱莉娅相当于什么?

Python, Java and Scala have ternary operators. What is the equivalent in Julia?

推荐答案

对于内联使用,一个? b:c存在,如前一个答案所述.但是,值得注意的是,Julia中的if-else-end在大多数Lisp方言中的工作方式与if if cond expr1 expr2一样,既充当if子句又充当三元运算符.这样,if-then-else返回执行的表达式的返回值.

For inline use, a ? b : c exists, as mentioned by the previous answer. However it is worth noting that if-else-end in Julia works just like (if cond expr1 expr2) in most Lisp dialects which acts both as the if-clause and as the ternary operator. As such, if-then-else returns the return value of the expression that gets executed.

意思是你可以写类似的东西

Meaning that you can write things like

function abs(x)
    if x > 0
        x
    else
        -x
    end
end

,这将返回您想要的内容.您不必使用return语句来中断功能块,只需返回if块返回的值即可.

and this will return what you want. You do not have to use a return statement to break the function block, you just return the value returned by the if-block.

内联,您可以编写

if (x > 0) x else -x end 

将返回与三元运算符表达式(x> 0)相同的东西吗? x:-x,但具有避免使用perl-ish?:符号的好处,并且通常更具可读性.

which will return the same thing as the ternary operator expression (x > 0) ? x : -x , but has the benefit of avoiding perl-ish ?: symbols and is generally more readable.

大多数语言的三元运算符与if-then-else分开,因为if子句是语句,而在类似lisp的语言中,它们是表达式,就像其他所有子句一样,并且具有返回值.

Most languages have a ternary operator separate from if-then-else because if clauses are statements, while in lisp-like languages they are expressions just like everything else and have a return value.

这篇关于朱莉娅有三元条件运算符吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆