Does Julia have a ternary conditional operator?

痞子三分冷 提交于 2019-12-11 04:24:45

问题


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


回答1:


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

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.

Inline, you can write

if (x > 0) x else -x end 

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.

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.




回答2:


Are you refering to this?

a = true
b = 1
c = 2

julia>a ? b : c
1

a = false 

julia>a ? b : c
2



回答3:


Yes! Julia has a ternary operator. Here is a quick example from the Julia docs Julia docs:

The so-called "ternary operator", ?:, is closely related to the if-elseif-else syntax, but is used where a conditional choice between single expression values is required, as opposed to conditional execution of longer blocks of code. It gets its name from being the only operator in most languages taking three operands:

a ? b : c The expression a, before the ?, is a condition expression, and the ternary operation evaluates the expression b, before the :, if the condition a is true or the expression c, after the :, if it is false. Note that the spaces around ? and : are mandatory: an expression like a?b:c is not a valid ternary expression (but a newline is acceptable after both the ? and the :).

The easiest way to understand this behavior is to see an example. In the previous example, the println call is shared by all three branches: the only real choice is which literal string to print. This could be written more concisely using the ternary operator. For the sake of clarity, let's try a two-way version first:

julia> x = 1; y = 2;

julia> println(x < y ? "less than" : "not less than")
less than

julia> x = 1; y = 0;

julia> println(x < y ? "less than" : "not less than")
not less than


来源:https://stackoverflow.com/questions/39790031/does-julia-have-a-ternary-conditional-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!