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

In Julia, is there a way to write a macro that compiles based on the (compile-time) type of its arguments, at least for arguments whose types can be inferred at compile time? For example, in the example below, I created a function called code_type that returns the compile time type x . Is there any function like this, or any way to produce this behavior? (Or macros expand before types are inferred, so this is not possible.)

 macro report_int(x) code_type(x) == Int64 ? "it an int" : "not an int" end 
+6
source share
2 answers

Macros cannot do this, but generated functions can.

Check out the docs here: http://julia.readthedocs.org/en/latest/manual/metaprogramming/#generated-functions

+8
source

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

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

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

+4
source

Source: https://habr.com/ru/post/987834/


All Articles