List splicing with foreach

Tcl’s foreach command is commonly used to iterate through items in a list. However, I had not realized that it can step through more than one list at once. Here’s a handy application of this property based on an example from the documentation:

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

This procedure combines two lists into a new list comprised of alternating items from each input:

% splice {a b c} {1 2 3}
a 1 b 2 c 3

One use for this is to join a list of keys to a list of values to establish a dictionary or an array:

% set dimensions [splice {length width height} {10 16 33}]
length 10 width 16 height 33

% dict get $dimensions height
33

% array set d $dimensions
% set d(width)
16

So if you’ve got an ordered list of values you’d like to access as named fields, you can combine it with a list of field names using foreach and be on your way.

Posted on Monday, April 28th, 2008. Tags: , .