I am trying to represent a hierarchy using namedtuple
. Essentially, every node has three attributes relevant to the hierarchy: parent
, leftChild
and rightChild
(they also have some attributes that carry the actual information, but that is not important for the question). The problem is the circular reference between parents and children. Since I need to specify all values at construction time, I run into problems because parents need the children to be constructed first, and children need the parents to be constructed first. Is there any way around this (other than using a custom class instead of tuples)?
views:
29answers:
3
A:
Remove parent field. You can still implement any tree-manipulation operations efficient without keeping reference to parent node.
Vadim Shender
2010-09-01 10:05:40
"Manipulation" doesn't exist for immutable types.
Ignacio Vazquez-Abrams
2010-09-01 10:08:47
@Vadim Shender: The whole point of this is to have convenient access to the hierarchy, so removing the parent field would defeat the original purpose.
Space_C0wb0y
2010-09-01 10:12:06
@Ignacio: Is functional programming just a myth?
Vadim Shender
2010-09-01 10:58:38
A:
One trick is not to use an object reference, but instead, a symbolic ID that you maintain in a hash table.
reinierpost
2010-09-01 11:41:12