TIP 200: Listing the Values in an Array

Login
Author:         Donal K. Fellows <[email protected]>
Author:         Dossy Shiobara <[email protected]>
State:          Rejected
Type:           Project
Vote:           Done
Created:        20-May-2004
Post-History:   
Keywords:       Tcl
Tcl-Version:    8.5

Abstract

This TIP proposes adding another subcommand to the array command to list the values in an array.

Rationale

Currently, the easiest ways of building a list of all values within an array involve either iterating over the names of the array elements and then reading the value at each step, or iterating over the result of array get and dropping the name part of each pair, as can be seen from these code examples:

set list {}
foreach name [array names SomeArray] {
   lappend list $SomeArray($name)
}

set list {}
foreach {name value} [array get SomeArray] {
   lappend list $value
}

Neither of these is especially efficient, since the first does a very large number of array reads, and the second builds a very large intermediate list (particularly if you subsequently want to filter the values to select a subset of them.)

It would be better if the functionality was added directly to the Tcl core, especially as the conceptual overhead would be very low as there are already subcommands of array for returning both the names of the array and the name/value pairs.

Proposed Change

I propose to add a new subcommand to array called values with the following syntax:

array values arrayName ?globPattern?

This returns a list of values that are contained in the array in the "natural order" of the values within the array. The optional globPattern argument allows for returning only some of the values in the array (those values for keys that match the pattern according to the rules of string match). The pattern will not change the ordering of the list; it only filters the result.

The order of the values returned shall be such that the following two foreach iterations shall behave identically (modulo traces on the array variable):

foreach {name value} [array get AnyArray $pattern] {
   AnyScript
}

foreach name  [array names  AnyArray $pattern] \
        value [array values AnyArray $pattern] {
   AnyScript
}

Note that this implies that the resulting list from array values may well contain duplicates, and that none of the values actually returned will necessarily match the supplied pattern.

Copyright

This document has been placed in the public domain.