Posted to tcl by colin at Sun May 23 23:54:21 GMT 2010view pretty

#       A combination of *dict with* and *apply*, this procedure creates a
    #       new procedure scope populated with the values in the dictionary
    #       variable. It then applies the lambdaTerm (anonymous procedure) in
    #       this new scope. If the procedure completes normally, then any
    #       changes made to variables in the dictionary are reflected back to
    #       the dictionary variable, otherwise they are ignored. This provides
    #       a transaction-style semantics whereby atomic updates to a
    #       dictionary can be performed. This procedure can also be useful for
    #       implementing a variety of control constructs, such as mutable
    #       closures.
    #
    proc apply {dictVar lambdaExpr args} {
	upvar 1 $dictVar dict
	set env $dict ;# copy
	lassign $lambdaExpr params body ns
	if {$ns eq ""} { set ns "::" }
	set body [format {
	    upvar 1 env __env__
	    dict with __env__ %s
	} [list $body]]
	set lambdaExpr [list $params $body $ns]
	set rc [catch { ::apply $lambdaExpr {*}$args } ret opts]
	if {$rc == 0} {
	    # Copy back any updates
	    set dict $env
	}
	return -options $opts $ret
    }