Macro - parse argument type from input string

I am trying to define this function (with “Int” as a string argument) through a macro

function my_function_name(x::Int)
    return x*x+one(x)
end

Here is my best try (which fails).
I realize this MWE is not meaningful. In my use case, the body of the function will be different (i.e. a different calculation) based on the type of x (say the output is x^2 for Int32 and x^3 for UInt8).

macro myMacro(tt)
    name="my_function_name"    
    out= quote        
        function $(esc(Symbol(name)))(x::$tt)
            return x*x+one(x)
        end
    end #end quote
    return out
end

@macroexpand @myMacro("Int")

@myMacro("Int")

Does typeof() not help here?

typeof(x)==Int32 && output=x^2
typeof(x)==UInt8 && output=x^3

Not for my use case. Certainly I can do one(typeof(x)).
But for my actual use case, the macro pulls parameters from a dataframe generating a polynomial used in a hot inner loop. And these parameters will depend on the type of x. Thus the body of the function will be different for each type of x.
I guess there might be other ways to approach my problem setting. But I would still like to know how (or if), I can write a macro which defines the function mentioned in my first snippet.

Ok. This does work.
I guess the question may come back to:
I can solve a problem by using “if then else”, a dictionary, multiple dispatch, …

Let us assume that I have 80 different types for which I have a different function body.
I wanted the functions to depend on the type of the input.
Certainly I can use 80 if conditions to achieve this. Would it be preferable over multiple dispatch?

You have to call your macro with a type, not a string, like this

julia> @myMacro Int
my_function_name (generic function with 1 method)

julia> my_function_name(3)
10

If you really want the macro to accept strings instead, you have to write your macro more like this:

macro myMacro(tt)
    name="my_function_name"    
    out= quote        
        function $(esc(Symbol(name)))(x::$(Meta.parse(tt)))
            return x*x+one(x)
        end
    end #end quote
    return out
end
1 Like

Thank you.

I had a mixup with Base.parse and Meta.parse earlier today. I now realize that these are different functions.