StructTypes.jl icon indicating copy to clipboard operation
StructTypes.jl copied to clipboard

Standard interface for programatic structure definition

Open aminya opened this issue 5 years ago • 0 comments

I think it would be useful to have a standard interface for programmatic structure. Here I give the basic structure, but StructTypes related features can be added to the functions.

1-time function

functions API:

struct_define(struct_name::Symbol; fields_names::Vector{Symbol}, fields_types::Vector{Union{DataTypes, Symbol, Missing})

Example

struct_define(:Foo, [:a, :b, :c], [:Int64, missing, :String])

over-time method

functions API:

struct_define(struct_data::StructConstructor) # defines a struct based on the data

mutable struct StructConstructor
   name::Symbol
   fields_names::Vector{Symbol} 
   fields_types::Vector{Union{DataType, Symbol, Missing}}
end

# a constructor for when we know the name and number of fields:
function StructConstructor(nfields::Integer)  
   fields_names = Vector{Symbol}(undef, nfields)
   fields_names = Vector{Union{DataType, Symbol, Missing}}(undef, nfields)
   return StructConstructor(:TempName, fields_names, fields_names)
end

function StructConstructor(name::Symbol, nfields::Integer)  
   fields_names = Vector{Symbol}(undef, nfields)
   fields_names = Vector{Union{DataType, Symbol, Missing}}(undef, nfields)
   return StructConstructor(name, fields_names, fields_names)
end

Example

mystruct_data = StructConstructor()
mystruct_data = mystruct_data.name = :Foo # adds name

names = [:a, :b, :c]
types = [:Int64, missing, :String]
for (name, type) in zip(types, names)
  push!(mystruct_data.fields_names, name)
  push!(mystruct_data.fields_types, type)
end
struct_define(mystruct_data)
mystruct_data = StructConstructor(:Foo, 3)
names = [:a, :b, :c]
types = [:Int64, missing, :String]
for ifield = 1:3
  mystruct_data.fields_names[ifield] = names[ifield]
  mystruct_data.fields_types[ifield] = types[ifield]
end
struct_define(mystruct_data) 

We can more feature such as

  • the default value for the fields
  • functions that check the values during the definition of an instance or updating

Related packages:

  • https://github.com/aminya/AcuteML.jl
  • https://github.com/mauro3/Parameters.jl
  • https://github.com/cstjean/QuickTypes.jl

aminya avatar Feb 28 '20 19:02 aminya