Seven Lines of Julia (examples sought)

In Julia v1.8 we’ll have the possibility of type-annotating global variables, to promise their type won’t change:

julia> x::Float64 = 3.14
3.14

julia> x = 2.71
2.71

julia> x = "hello world"
ERROR: MethodError: Cannot `convert` an object of type String to an object of type Float64

Wouldn’t it be nice if we could automatically get the type annotation without having to explicitly type it ourselves? Here be dragons macros (note that the macro definition is exactly 7 lines):

julia> macro stable(ex)
           ex.head !== :(=) && throw(ArgumentError("@stable: `$(ex)` is not an assigment expression."))
           quote
               local x = $(esc(ex.args[2]))
               $(esc(ex.args[1]))::typeof(x) = x
           end
       end
@stable (macro with 1 method)

julia> @stable y = "hello world"
"hello world"

julia> y
"hello world"

julia> y = "foo bar"
"foo bar"

julia> y = 1 + 2
ERROR: MethodError: Cannot `convert` an object of type Int64 to an object of type String

Thanks @Mason for the tip in Zulip about local and the suggestion for the name of the macro (I initially called it @auto, like the C++ auto keyword).

38 Likes