TIP 58: Extend [set] to Assign Multiple Values to Multiple Variables

Login
Author:         Anselm Lingnau <[email protected]>
State:          Rejected
Type:           Project
Vote:           Done
Created:        02-Sep-2001
Post-History:   
Tcl-Version:    8.5

Abstract

This TIP proposes a multiple assignment command as a backwards-compatible extension to the Tcl set command.

Introduction

Often one needs to assign values to several variables in close proximity. Right now several set commands are necessary:

  set a 123
  set b 456

or

  set a 123; set b 456

Or one abuses the foreach command:

  foreach {a b} {123 456} break

However, by analogy to the variable and array set commands, the following would be useful:

  set a 123 b 456

This would assign 123 to the variable a and 456 to the variable b.

Note that this extension is backwards-compatible to existing uses of the set command since until now only one or two arguments to set were allowed.

Specification

The set command is extended to allow either one or an even number of arguments. The behaviour in the case of one argument remains the one documented in the set manual page; when an even number of arguments is specified, the behaviour of set v0 e0 ... vn en is identical to that of the sequence of commands set v0 e0; ...; set vn en according to the traditional semantics, except that the way Tcl processes commands means that e0 ... en are all evaluated before any assignments are performed. I.e., the commands

  set a 1
  set a 2 b $a
  puts $b

print 1, not 2. If this is an issue you must use separate set statements.

The command set v0 e0 ... vn en returns the value of en.

Rationale

This extension is an obvious analogy to the variable and array set commands of Tcl, both of which allow an alternating list of names and expressions to be given as arguments. It is completely backwards-compatible (set invocations with more than two arguments used to be syntax errors) and very easily implemented.

This extension in no way prejudices against the adoption and use of other multiple-assignment commands, such as lassign (see [57]). In particular, the set extension is unsuitable for assigning a list result to a number of variables element by element. However, its simplicity and consistency to other similar Tcl commands is appealing.

Reference Implementation

A patch to Tcl 8.4a3 which implements the set extension may be found at http://anselm.our-isp.org/set-patch.diff - a patched Tcl 8.4a3 passes the Tcl 8.4a3 regression test suite with no test failures. No test cases nor documentation for the set extensions have been devised yet but this is easy to do once there is a consensus that this feature is actually desirable.

Copyright

This document is placed in the public domain.