Stream: helpdesk (published)

Topic: Multiple val types with @eval (maybe?)


view this post on Zulip Kevin Bonham (May 21 2021 at 16:04):

I'm trying to use a Val type to make some data cleaning operations a bit easier. Here's what I have so far:

struct ObsType{x} end

ObsType(s::Symbol) = ObsType{s}()
ObsType(s::AbstractString) = ObsType(Symbol(s))

_fix_val(val, ::ObsType) = val
_fix_val(val::AbstractFloat, ::ObsType{:timepoint}) = floor(Int, val)
_fix_val(val::AbstractString, ::ObsType{:timepoint}) = parse(Int, val)

This works great, and allows me to do stuff like df[!, col] = _fix_val.(df.col, ObsType{col}), regardless of what col is. Cool.

But now I have several "date-like" column names that I'd like to treat all in the same way. I was thinking I could maybe do this:

# I need this tuple for other purposes, so I thought I could re-use it
const _date_priority = (:collectionDate,
                        :CollectionDate,
                        :assessmentDate,
                        :scanDate,
                        :Date,
                        :momDate)

function _parse_date(datestring)
    occursin("/", datestring) && return Date(datestring, Dates.DateFormat("m/d/y"))
    throw(ArgumentError("Invalid date string: $datestring"))
end

for d in _date_priority
    @show d
    @eval _fix_val(val::AbstractString, ::ObsType{d}) = _parse_date(val)
end

but this gives me UndefVarError: d not defined. I also tried $d, but this gives me UndefVarError: collectionDate not defined. That's the extent of my debugging eval ability :sweat_smile:

view this post on Zulip Takafumi Arakaki (tkf) (May 21 2021 at 22:05):

I think you need $(QuoteNode(d))

view this post on Zulip Mason Protter (May 21 2021 at 22:31):

This is basically a quirk of Expr and Symbol inside eval or when returned from macros. You need QuoteNode to signal to julia that the Symbol is meant to be interpreted as a symbol rather than as a variable name.

view this post on Zulip Takafumi Arakaki (tkf) (May 21 2021 at 22:46):

I tend to think it's more like a universal pain that comes with AST manipulation (and not just Julia's Expr). I imagine you'd need some kind of quote/unquote machinery when dealing with AST in general.

view this post on Zulip Brian Chen (May 21 2021 at 22:56):

Quasiquoting in particular never fails to give me a headache :P

view this post on Zulip Mason Protter (May 21 2021 at 23:00):

Yes of course. I just mean that it's a quirk of using elements of the AST in code. Not that we did something wrong with Expr and Symbol

view this post on Zulip Takafumi Arakaki (tkf) (May 21 2021 at 23:09):

Ah, yes, you mentioned "quirk ... inside eval." Totally agree Expr and Symbol are more quirky in eval.


Last updated: Dec 28 2024 at 04:38 UTC