Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Julia, can a macro access the inferred type of its arguments?

Tags:

julia

In Julia, is there a way to write a macro that branches based on the (compile-time) type of its arguments, at least for arguments whose types can be inferred at compile time? Like, in the example below, I made up a function named code_type that returns the compile-time type of x. Is there any function like that, or any way to produce this kind of behavior? (Or do macros get expanded before types are inferred, such that this kind of thing is impossible.)

macro report_int(x)
  code_type(x) == Int64 ? "it's an int" : "not an int"
end
like image 648
Jeff Avatar asked May 24 '15 21:05

Jeff


2 Answers

Macros cannot do this, but generated functions can.

Check out the docs here: https://docs.julialang.org/en/v1/manual/metaprogramming/#Generated-functions-1

like image 122
spencerlyon2 Avatar answered Oct 19 '22 19:10

spencerlyon2


In addition to spencerlyon2's answer, another option is to just generate explicit branches:

macro report_int(x)
    :(isa(x,Int64) ? "it's an int" : "not an int")
end

If @report_int(x) is used inside a function, and the type of x can be inferred, then the JIT will be able to optimise away the dead branch (this approach is used by the @evalpoly macro in the standard library).

like image 7
Simon Byrne Avatar answered Oct 19 '22 20:10

Simon Byrne