If and symbol, bug or feature?

Hi,

first of all many thanks for Julia … what a great language!

As I could not find this issue, I post it here:
When using an if statement with a symbol, the parser seems to understand it differently as I would:

if true :a else :b end

results in an UndefVarError: a not defined (tested in Julia 1.6 and 1.7).
Everything works fine when using Symbol(:a) or return :a instead. @code_lowered for the above form gives
CodeInfo(
1 ─ %1 = true:Main.a
└── goto #3 if not %1
2 ─ return nothing
3 ─ return :b
)

Not even sure what this would mean? Is that interpretation intended?

1 Like
if true 
    :a
else 
    :b 
end

yields

:a

But even the form if true :a; else :b; end results in the mentioned error. I’m perplexed.

if true; :a else :b end

works as “intended”

3 Likes
julia> if true; :a; else; :b; end
:a

I guess it’s just a parsing corner case with what : binds to which probably doesn’t come up to often as people tend to not write if ... else ... end statements as one liners (as that’s what true ? :a : :b is for)

3 Likes

To clarify, it is parsed as if (true:a) else :b end.

There seems to be several inconsistencies… These all fail:

julia> if true :a end
ERROR: UndefVarError: a not defined

julia> if true (:a) end
ERROR: syntax: space before "(" not allowed in "true (" at REPL[29]:1

julia> if true [1] end
ERROR: syntax: space before "[" not allowed in "true [" at REPL[31]:1

julia> if true (1,) end
ERROR: syntax: space before "(" not allowed in "true (" at REPL[32]:1

while these work:

julia> if true Symbol('a') end
:a

julia> if true "a" end
"a"

julia> if true 1 end
1

julia> if true 'a' end
'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)

julia> if true `a` end
`a`

julia> if true hypot(1,2) end
2.23606797749979

Please find an issue…

1 Like

Thanks, I have opened an issue.

1 Like