Reputation: 4401
When implementing a recursive data structure like TREE, I need a common attribute per TREE, and I wonder how to implement it:
once
attribute, I get only one shared attribute for all TREEs, not one per TREE.Is there any elegant Eiffel-style solution for that?
Upvotes: 1
Views: 85
Reputation: 5810
A tree has a distinguished root node that can be used to store information related to the whole tree rather than to a specific node. In order to retrieve this information, there should be a possibility to reach the root node from any other node of the tree. One possible solution is to have a feature parent
that would return the parent node of the specified node (or Current
for the root). Then, the feature that obtains the root node can look like
root: TREE
-- The root of the tree.
local
p: TREE
do
from
Result := Current
p := parent
until
Result = p -- `Result = Result.parent` when `Result` is root.
loop
Result := p
p := p. parent
end
ensure
Result.parent = Result -- `Result` has no other parent.
end
Then the tree-specific attribute value can be retrieved from an arbitrary tree node n
with n.root.my_attribute
.
EDIT:
Another possibility is to have a dedicated CELL
with the required data, and all nodes in the tree simply refer to this cell. The benefit is that no reference to the parent node is need and the access to the data is immediate.
Upvotes: 0