Gnocl Cookbook‎ > ‎

List Splicing and Creating Tagged Tables

Tcl’s foreach command is really useful when its necessary to iterate through items in a list. But, it is possible to use foreach to step through more than one list. This is really useful when its necessary to splice together related pieces of information contained in two separate lists, data tags for example.

proc splice {l1 l2} {
    foreach i $l1 j $l2 { lappend res $i $j }
    return $res
}

Suppose the intepreter returns a list of values, lets say the geometry of a widget as {10 20 400 300} which are known to be the x and y screen coordinates followed by the width and height. This information can then be spliced together using

% splice {x y w h} {10 20 400 300}
a 1 b 2 c 3

The usefulness of this comes from being able to use the spliced list as an argument to either the array or dict commands and the data restrieved in some meaningful way.

% array set geometry [ splice {x y w h} {10 20 400 300} ]
% set $geometry(h)

 300

Or,

% set geometry [ splice {x y w h} {10 20 400 300} ]
% dict get $geometry w

400

The usefulness of this comes into its own when handling larger data sets, perhaps the contents of a gnocl::list. Applying the get subcommand to a list object will return the data but it will not be tagged in anyay. Indeed, the column titles are purely desriptive and for the benefit of the user rather than data management. The following snippet shows how a simple table, ie a list of lists can be tagged using splicing.

set table {
{a {b B} c}
{d {e E} f}
{g {h H} i}
{j {l L} m}
}

set tags {1 2 3}

proc tag_table {tags table} {
foreach row $table {
set str ""
foreach i $tags j $row {
            append str "$i \{$j\} " }
append res $str\n
}
return [string trim $res] ;# remove the last newline
}

puts [tag_table $tags $table]









Comments