Walking Nested Records and Lists

Recursive traversal can visit values in nested records by handling containers and leaf values according to their shape.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace a path to a value
  2. Check shared or cyclic structures
  3. Preserve paths while walking mixed containers
  4. Treat shared objects and cycles deliberately

Trace a path to a value

In a record with field items holding two names, a leaf path can record the field name and the element index. For the second name the offset is one. Record fields and zero-based indices contribute different path components.

Check shared or cyclic structures

A tree-shaped serialized input has finite containment. A live object may share a container or point back to itself. Decide whether paths or distinct objects are being visited, and track identity for cycle detection when that representation permits cycles.[1]

Preserve paths while walking mixed containers

A JSON-shaped document may contain an object field items pointing to a list of records. A path like items[1].code identifies the second record's code. Carry the path as keys and indices while descending; assemble its display once a leaf is found. See stable record identifiers.

Object keys: items
List indices: 0, 1
Leaves: items[0].code = "A", items[1].code = "B"
Rejected second code can be reported at items[1].code

Treat shared objects and cycles deliberately

Plain parsed JSON forms a tree. Objects assembled in memory can point to themselves or share a child. If the operation enumerates paths, two references to one child may need two outputs. A path-local cycle check avoids looping without collapsing every shared path.

References

  1. Jeff Erickson, Algorithms ↩