How to do one-liners and other short conditionals?


#1

Sometimes I want to write a quick and dirty conditional, i.e.

munge_data!(x,y) if isempty(x)

But instead you have to write:

if isempty(x) munge_data!(x,y) end

// which I don’t think is as readable.


How do other people approach this?

Would it be nearly impossible to add this to the language?


#2

You could use short circuiting,

isempty(x) && munge_data!(x, y)

#3

Yeah, using && for that is a little reminiscent of C but is a pretty common idiom in julia code and very compact. You can also use || to get “unless” behavior, i.e.:

isvalid(arg) || throw(ArgumentError("Bad argument!"))

#4

what about this use case:

julia> isapprox(0, tau_exponent) && tau_exponent = 1

ERROR: syntax: invalid assignment location "isapprox(0,tau_exponent)&&tau_exponent"

#5
isapprox(0, tau_exponent) && (tau_exponent = 1)

#6

Thanks all :pray:

One last question:

Is this done widely enough to be considered idiomatic?


#7

It is used often. Consider it a tool.


#8

We have an explicit design rule for this in LightGraphs which says that shortcuts are preferred if the function is non-mutating. Therefore,

foo && return bar

is ok, but

foo && (baz += 1)

is not.


#9

I agree with this sentiment, but feel like it uncovers the problem.

Shouldn’t there be a quick way to write:

baz += 1 if foo

?

// I think the reason you’re against it is because it’s overly implicit


#10

Nothing’s stopping you from writing

foo && (baz += 1)

… it’s just that we discourage that practice in the package I help maintain. It’s a style thing, not a language limitation.


#11

Allow me to short-circuit the discussion and point to the relevant issues: #6823 and #16389. Happy reading!


Syntactic sugar: (x==2) and y=12 ; or even (x == 2) && y=12