I'm trying to create a convenience copy-paster with eval to not have to type out many function definitions at once but I get into problems with parametric types where I want to omit the parametric type in the signature. Probably easier to understand from the MWE below :)
julia> module TestMod
export A, B, f, ff
struct A{T}
x::T
end
struct B{T}
str::String
a::A{T}
end
# This is legal
ff(b::B, ::Type{A}) = b.a
# But doing the same thing with eval is not??
for fn in fieldnames(B)
ft = Symbol(first(eachsplit(string(fieldtype(B, fn)), '{')))
@info "Try to create function with $ft"
@eval TestMod f(b::B, ::Type{$ft}) = b.$fn
end
end
WARNING: replacing module TestMod.
[ Info: Try to create function with String
[ Info: Try to create function with Main.TestMod.A
ERROR: UndefVarError: `Main.TestMod.A` not defined
Stacktrace:
[1] top-level scope
@ none:1
Is there a way to get the above to work?
Figured it out. The module qualifier was what made it not work somehow. This works:
julia> module TestMod
export A, B, f, ff
struct A{T}
x::T
end
struct B{T}
str::String
a::A{T}
end
# This is legal
ff(b::B, ::Type{A}) = b.a
# But doing the same thing with eval is not??
for fn in fieldnames(B)
ftt = first(eachsplit(string(fieldtype(B, fn)), '{'))
ft = Symbol(last(split(string(ftt), '.')))
@info "Try to create function with $ft"
@eval TestMod f(b::B, ::Type{<:$ft}) = b.$fn
end
end
[ Info: Try to create function with String
[ Info: Try to create function with A
Main.TestMod
DrChainsaw has marked this topic as resolved.
Last updated: Nov 22 2024 at 04:41 UTC