Hi,
I’m trying create “dynamic” functions with macro, but it isn’t working. Let-me explain:
I’ve this function:
function f(::Type{T}, message) where T
println("Type: ", T)
println("Message: ", message)
end
When I call it f(Int, "Hi"), the output is:
Type: Int64
Message: Hi
Nice! Now I have the dictionary:
map = Dict( Int => "Hello", Float64 => "Hey!", UInt => "Bye" );
And I want dynamic create a function f2(Int), f2(Float64) and f2(UInt) based at map values.
Something like this that works fine, but at this case this f2 will only generate the cases that I manualy added at this code:
macro create_desired(map)
return esc(Expr(:block, [
:( f2(::Type{Int}) = f(Int, map[Int]) ),
:( f2(::Type{Float64}) = f(Float64, map[Float64]) ),
:( f2(::Type{UInt}) = f(UInt, map[UInt]) ),
]...))
end
After @create_desired(map), when I call f2(Int), f2(Float64) and f2(UInt), the output is respectly:
Type: Int64
Message: Hello
Type: Float64
Message: Hey!
Type: UInt64
Message: Bye
If you read at this point, I think do you know what I want. I tried something like this, but it isn’t working:
macro create(map)
return esc(Expr(:block, [
:( function f2(::Type{T}) where T
return f(T, msg)
end
for (T, msg) in map )
]...))
end
I think it’s a problem with scope at this code. And tried this:
macro create2(map)
exprs = []
:(
for (T, msg) in $map
push!($exprs, function f2(::Type{T}) where T
return f(T, msg)
end )
end
)
return esc(Expr(:block, exprs...))
end
Someone, know how to solve this problem?