Representing recursive structs


#1

I’m trying to represent mutually recursive structs in Ruby to model this data:

{
  "data": 123,
  "next": {
    "data": 234,
    "next": {
      "data": 3456,
      "next": null
    }
  }
}
class List < Dry::Struct
  attribute :data,      Types::Strict::Int
  attribute :next, Types.Instance(Next).optional
end

class Next < Dry::Struct
  attribute :data,      Types::Strict::Int
  attribute :next, Types.Instance(List)
end

But Ruby errors because Next is referenced before it’s defined. How do you recommend breaking cycles like this when using dry-types?


#2

Nevermind! I’ve forward-declared the structs with:

# (forward declaration)
class List < Dry::Struct; end

# (forward declaration)
class Next < Dry::Struct; end

#3

I think this should be good enough for you but in future there can be complications with recursive data types. For instance, we’ll need to figure out how to dump them to AST properly.