stochastic learner
stochastic learner

Reputation: 199

Ternary operator for multiple conditions in Julia

I have Julia code as shown

if cxp1_v1 < cxp1_v2 
    d_min = cxp1_v1 
    d_max = cxp1_v2 
else 
    d_min = cxp1_v2
    d_max = cxp1_v1 
end

or

if cxp1_v1 < cxp1_v2 d_min, d_max = cxp1_v1, cxp1_v2 else d_min,  d_max  = cxp1_v2, cxp1_v1 end

Is there a way to accomplish this same in the ternary operator? I tried something like as shown

cxp1_v1 < cxp1_v2 ? d_min, d_max = cxp1_v1, cxp1_v2:d_min,  d_max  = cxp1_v2, cxp1_v1

but I get

syntax: colon expected in "?" expression

Stacktrace:
 [1] top-level scope
   @ In[422]:11
 [2] eval
   @ ./boot.jl:373 [inlined]
 [3] include_string(mapexpr::typeof(REPL.softscope), mod::Module, code::String, filename::String)
   @ Base ./loading.jl:1196

Upvotes: 3

Views: 249

Answers (1)

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69839

cxp1_v1 < cxp1_v2 ? (d_min, d_max) = (cxp1_v1, cxp1_v2) : (d_min, d_max) = (cxp1_v2, cxp1_v1)

but I would probably write it as:

d_min, d_max = cxp1_v1 < cxp1_v2 ? (cxp1_v1, cxp1_v2) : (cxp1_v2, cxp1_v1)

since it seems a bit easier to read, or even:

d_min, d_max = minmax(cxp1_v1, cxp1_v2)

Upvotes: 8

Related Questions