TIP 224: Add New [array] Subcommand 'value'

Login
Bounty program for improvements to Tcl and certain Tcl packages.
Tcl 2019 Conference, Houston/TX, US, Nov 4-8
Send your abstracts to [email protected]
or submit via the online form by Sep 9.
Author:         Peter MacDonald <[email protected]>
Author:         Robert Seeger <[email protected]>
Author:         Donal K. Fellows <[email protected]>
State:          Rejected
Type:           Project
Vote:           Done
Created:        28-Sep-2004
Post-History:   
Tcl-Version:    8.7
Tcl-Branch:     tip-224
Votes-For:      DKF, JN, SL
Votes-Against:  DGP, AK
Votes-Present:  FV
Rejection-Reason:
	Tcl 8.7 already has a new [array default] command from TIP 508. It
	does not appear to interact with the proposed [array value] in a
	sensible way.

Abstract

The TIP proposes the addition of a new subcommand to the array command: value. The value subcommand would query, reference, and/or initialize an array element with more options for complexity than a simple read.

Rationale

TIP 215 proposed modifying the incr command to auto-initialize variables which do not exist, rather than throwing an error. After some debate, it was identified that frequency counting in arrays was the primary area of interest. In particular, the excessive use of if/info exists constructs in such code is inefficient, verbose and rather difficult to read. Though now we have incr doing automatic initialization, the addition of an extra subcommand could substantially reduce the complexity of much Tcl code.

Specification

A new subcommand will be added to array, being value.

array value var elem ?value? ?init?

The array value would just return the current contents of the element elem of the array called var if it exists, or value otherwise. If the init parameter is provided and resolves to true (as determined by Tcl_GetBooleanFromObj() of course), the variable is initialized to value if it doesn't already exist. The default for value is the empty string, and the default for init is false.

Reference Implementation

Following is an example Tcl-only implementation of the value subcommand:

proc Array {cmd var elem {amt {}} {init 0}} {
   # Implement the Array subcmd value on var(elem):
   #  - value  return the value if defined, else return amt
   #           initializing if init.
   upvar $var uvar
   if {[string match $cmd* value]} {
      if {[info exists uvar($elem)]} {
         return $uvar($elem)
      }
      if {$init} {
         return [set uvar($elem) $amt]
      }
      return $amt
   } else {
      error "usage: Array value var elem ?amt? ?init?"
   }
}

Discussion

Copyright

This document has been placed in the public domain.