How to do one-liners and other short conditionals?

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?

You could use short circuiting,

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

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!"))
3 Likes

what about this use case:

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

ERROR: syntax: invalid assignment location "isapprox(0,tau_exponent)&&tau_exponent"
isapprox(0, tau_exponent) && (tau_exponent = 1)
3 Likes

Thanks all :pray:

One last question:

Is this done widely enough to be considered idiomatic?

It is used often. Consider it a tool.

5 Likes

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.

2 Likes

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

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.

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

2 Likes