djsegal
September 27, 2017, 1:21am
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?
You could use short circuiting,
isempty(x) && munge_data!(x, y)
6 Likes
ssfrr
September 27, 2017, 3:05am
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!"))
3 Likes
djsegal
September 27, 2017, 3:36am
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"
isapprox(0, tau_exponent) && (tau_exponent = 1)
3 Likes
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
djsegal
September 27, 2017, 6:51pm
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
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