Col*_*ers 7 ternary-operator julia
在Julia中,我可能想编写一个函数,0如果输入小于1,则返回,2如果输入大于或等于,则返回1.这是一个非常简单的函数,五行if else结构的冗长可能过多.所以我试图把它变成一个单行函数.我能想到的最好的是:
f(x::Number) = begin (x < 1) && return(0); return(2); end
Run Code Online (Sandbox Code Playgroud)
要么
f(x::Number) = begin x < 1 ? (y=0) : (y=2); return(y); end
Run Code Online (Sandbox Code Playgroud)
有没有更简单的方法来定义这个功能?
spe*_*on2 11
julia> f(x::Number) = x < 1 ? 0 : 2
f (generic function with 1 method)
julia> f(0)
0
julia> f(1)
2
julia> f(0.99)
0
Run Code Online (Sandbox Code Playgroud)