Stream: helpdesk (published)

Topic: ✔ eval function with parameterized type


view this post on Zulip DrChainsaw (Feb 19 2023 at 13:27):

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?

view this post on Zulip DrChainsaw (Feb 19 2023 at 13:38):

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

view this post on Zulip Notification Bot (Feb 19 2023 at 13:38):

DrChainsaw has marked this topic as resolved.


Last updated: Dec 28 2024 at 04:38 UTC