Advice for building nested objects

Hello, I am looking for some advice on how to set up nested objects in Julia.

For example, if I wanted to create “schoolchildren” (with variables “age”, “testGrade”,“favouriteSubject”) which are then grouped into “classrooms” (with variables “numberOfStudents”,“averageTestGrade”,“mostPopularSubject”), which are then nested into a single “school”, what sort of data structures should I use for each level, and how would I implement them?

As may be obvious I would want the “classrooms” to be able to accumulate meta-data about the “schoolchildren” in them.

Structs seem an easy match for the schoolchildren but I’m not sure if they’ll apply to the higher-level objects.

Thanks in advance.

you might start with this and modify it to suit your needs

mutable struct Child
  firstname::String
  lastname::String
  age::Int
  testgrade::String
  metadata::String
end

struct Classroom
  children::Vector{Child}
end

numberofstudents(x::Classroom) = length(x.children)

struct School
  classrooms::Vector{Classroom}
end

numberofclassrooms(x::Classroom) = length(x.classrooms)

const Grades =
  Dict("A+" => 1, "A" => 2, "A-" => 3,
       "B+" => 4, "B" => 5, "B-" => 6)

function averagetestgrade(x::School)
    gradesum = 0
    gradecount = 0
    for class in x.classrooms
        for student in class.children
            gradesum   += Grades[student.testgrade]
            gradecount += 1
        end
    end
    return gradesum / gradecount
end

AmyAmile = Child("Amy", "Amile", 10, "A")
BillyButton = Child("Billy", "Button", 10, "B+")
CindyConnoly = Child("Cindy", "Connoly", 10, "A-")

mathclass   = Classroom([AmyAmile, BillyButton, CindyConnoly])
civicsclass = Classroom([BillyButton, CindyConnoly])

school = School([mathclass, civicsclass])

I’m sure you know that, full scale, this sort of app is usually done using a database.

3 Likes

This looks great, I’ll give it a try. Thanks a bunch!