Trouble understanding macros: creating a struct on the fly

So I ended up writing the following functions to make my datatype and to slurp in my array of datatypes from disk.

function make_schema_struct_expr(dataset::String)
    function schema_helper(element)
        :($(Symbol(element[1]))::$(Symbol(titlecase(element[2]))))
    end
    schema=open(JSON.parse, "/path/to/data/$dataset/schema.json", "r")
    Expr(:type, false
        , Symbol(dataset)
        , Expr(:block, map(schema_helper, schema)...))
end
    
function load_dataset{T}(dataset::Type{T}, datafile_name)
    filepath = "/path/to/data/$dataset/$datafile_name"
    num_records::Integer = stat(filepath).size / sizeof(dataset)
    open(f->read(f, dataset, num_records), filepath, "r")
end

and then I just make sure I eval the struct and then load in my data.

eval(make_schema_struct_expr("MyDataset"))
dat = load_dataset(MyDataset, "file_0.dat")

I bet I can do this even more cleanly but this feels like a win. Thank you @cstjean for your help! =D

1 Like