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

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

问题描述

Python、Java 和 Scala 都有三元运算符.Julia 中的等价物是什么?

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

推荐答案

对于内联使用,一个 ?b : c 存在,如上一个答案所述.然而值得注意的是,Julia 中的 if-else-end 就像大多数 Lisp 方言中的 (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, but less chainable.

大多数语言都有一个与 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.

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

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