Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Standard interface for programatic structure definition #7

Open
aminya opened this issue Feb 28, 2020 · 0 comments
Open

Standard interface for programatic structure definition #7

aminya opened this issue Feb 28, 2020 · 0 comments

Comments

@aminya
Copy link

aminya commented Feb 28, 2020

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:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant