Tree Dict-Array
A tree node key is usually thought of as containing
a simple value. This value however can contain a complex dict or array value.
A dict-array is
a new object-type based on a hashtable.
The
values in a tree-array are indexed using the
familiar array notation. This is generally usable
anywhere key names are acceptable, eg:
set t [tree create]
set id [$t insert end]
$t set $id Users {Name Bill Age 19 Sex M}
$t set $id Users(Name) "William"
$t incr $id Users(Age)
Array Support
Virtually all commands that take a key
will also take an array indexed key.
The tree with sub-command also has
support for arrays via the -array option.
The find sub-command makes it easy to
find all node/keys that are (or are not) arrays, eg
set isa [$t find all -key Users -isarray]
set nota [$t find all -key Users -isarray -invert]
Dicts
If a dict value is assigned to a key value,
it will be preserved and used during array access.
One advantage of using a dict is that it preserves order.
Unlike dict a tree-array does not
store key names as objects.
It stores only the key value as an object.
In practice however, users should not have to worry
about this distinction.
List-Array Conversions
Array objects used in list
contexts automatical convert to the required type.
However, Tcl will end up doing a split on the
string representation. This generally loses any type information.
One way around this is
to use the values command.
The following example
shows how to get array values
as a list directly:
set t [tree create]
$t set root a(x) 1 a(y) 2
set i [$t insert 0]
$t set $i x [$t values 0 a True]
$t set $i y [$t get 0 a]
puts "TYPES: [$t type $i x], [$t type $i y]"
% TYPES: list, array
ie. the 4th arg to the values command enables
efficient coercion of
array values to a list values.
© 2008 Peter MacDonald