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:
I think you need $(QuoteNode(d))
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.
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.
Quasiquoting in particular never fails to give me a headache :P
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
Ah, yes, you mentioned "quirk ... inside eval
." Totally agree Expr
and Symbol
are more quirky in eval.
Last updated: Nov 06 2024 at 04:40 UTC