I often find myself wishing the following syntax worked: if a < 0 then a = 0 (get the condition, and statement that follows, on a single line. No need for end or ;)
This works fine: if a < 0; a = 0; end, but feels just a tad cumbersome.
a < 0 ? a = 0 : nothing works as well, but I don’t love the nothing.
(a < 0) && (a = 0) also works but the need for the parentheses is disappointing.
What is the most Julianic way to do this simple “if-then” logic?
julia> macro ifthen(condition, body)
quote
if $(esc(condition))
$(esc(body))
end
end
end
@ifthen (macro with 1 method)
julia> a = 1
1
julia> @ifthen a > 0 a = 0
0
julia> a
0
In my experience all other versions of if were slower then a = a < 0 ? 0 : a, I guess because it converts to a single operation. But may be my benchmarking was off.
The particular condition and statement were just hypothetical. Usually my conditions and the statement are more complicated. The essence of the question was the style for a single-line if.
I wasn’t trying to save typing. I want to save vertical space.
I find it easier to read code when I don’t have to scroll around. When the if-then is fairly simple, it’s not hard to grok it when it’s on one line. So I was looking to squeeze it onto a single line without abusing && (if that is a thing) and using a syntax that was aesthetically sound.
I don’t think I can expand much on what I wrote above. You are changing the value of a variable, so it should stand out.
Note that idiomatic Julia code often has shorter functions than other languages used for a similar purpose (eg R, and particularly Matlab). Functions longer than, say, 30 LOC are quite rare, or should be.
Prefer the short circuiting conditional over if / else when convenient, and where state is not explicitly being mutated ( e.g. , condition && error("message") is good; condition && i += 1 is not).
It’s a hard and fast rule for LightGraphs but not universal across the Julia ecosystem as far as I’ve seen.