A fun one for the new year
One of the things I really like about Julia is being able to write code how I like (and the surprisingly large number of language decisions I find myself loving). The syntax is natural, I can add or subtract lines and indent however I feel is most appropriate in the momentâwhether for brevity or for verbosityâI donât need a bunch of extra parentheses and braces, matrix building is amazing, tuple destructuring, macros and generated functions are awesome, string and expression interpolation, builtin big numbers, regular expressions, complex numbers, letâs not forget the type system!.. I can go on for days. Itâs amazing how much expressivity Juliaâs creators were able to pack into a single language, and a high performance one at that!
But that superpower also comes with some [all things considered, a surprisingly small number of] gotchas that can be unexpected sometimes, and you might spend some time debugging before you figure out what happened. The parsing rules are amazing, in that remarkably concise syntax gets you what you want most of the time and that makes up for the times when you didnât get what you expected; but it means you have to be careful sometimes.
Iâll list some things Iâve bumped into:
1. Sometimes Subtraction
julia> @show 1-2+3
(1 - 2) + 3 = 2
2
julia> @show 1 -2+3
1 = 1
-2 + 3 = 1
1
julia> @show 1 -2 +3
1 = 1
-2 = -2
3 = 3
3
julia> @show 1- 2+ 3
(1 - 2) + 3 = 2
2
2. Curry Me Maybe
julia> [<(5) cos]
1Ă2 Matrix{Function}:
Fix2{typeof(<), Int64}(<, 5) cos
julia> [cos <(5)]
ERROR: MethodError: no method matching isless(::typeof(cos), ::Int64)
3. Symbol Swap
julia> s = 2 > 1 ? :Hello : :World
:Hello
julia> if 2 > 1 s=:Hello else s=:World end
:Hello
julia> s = if 2 > 1 :Hello else :World end
ERROR: UndefVarError: Hello not defined
4. Tuple Trouble
julia> f() = (local a, b = 1, 2; a+b)
f (generic function with 1 method)
julia> f() = (a, b = 1, 2; a+b)
ERROR: syntax: unexpected semicolon in tuple around REPL[2]:1
5. Parenthetically Speaking
julia> for x=1:3 print("$x ") end
1 2 3
julia> for x=(1,2,3) print("$x ") end
1 2 3
julia> for x=1:3 (print("$x ")) end
1 2 3
julia> for x=(1,2,3) (print("$x ")) end
ERROR: syntax: space before "(" not allowed in "(1, 2, 3) (" at REPL[4]:1
6. Called It
julia> (4)(4)
16
julia> (4)(2*2)
16
julia> (2*2)(4)
ERROR: MethodError: objects of type Int64 are not callable
7. Poly vs Bi
julia> +(1, 2, 3)
6
julia> -(1, 2, 3)
ERROR: MethodError: no method matching -(::Int64, ::Int64, ::Int64)
8. Enter the Matrix
julia> if 1 > 2 A=[1 2; 3 4] else A=[4 3; 2 1] end
2Ă2 Matrix{Int64}:
4 3
2 1
julia> A = if 1 > 2 [1 2; 3 4] else [4 3; 2 1] end
ERROR: syntax: space before "[" not allowed in "2 [" at REPL[2]:1
Thankfully parsing surprises are better than runtime surprises, and many of these are avoided with a strategic semicolon.
Are there any syntax surprises and gotchas that should be added to the list? Post them below!