let - a simpler sugar for expr

Sarnold 2005-11-10 -- The purpose is to offer a simple let command that works very much like C assignements for basic computations. The goal is not to join the general thing, but rather to keep it simple for everyday work.

Here is how it works :

 let varname assignment arg ...
 When assignment equals the '=' string, behaves like 'set varname [expr arg ...]'.
 When assignment is the '=' string following an operator like +, -, *, / or %,
 it behaves like 'set varname [expr {$varname <operator> args}]' 
% let a = 10
10
% let a = $a - 1
9
% puts $a
9
% let a *= 2
18

Please note that arguments do not have to be distinct. You can write this:

let a = $a+2

or this:

let a = 3 * 4

and even:

let a = {$b*cos($d)}

It is better to enclose expr-essions into braces when they contain variables.


Here it is :

 proc let {varname assign args} {
     upvar $varname leftvalue
     if {[llength $args]==1} {
         set args [lindex $args 0]
     }
     set args [uplevel expr $args]
     switch -exact -- $assign {
         += {set leftvalue [expr {$leftvalue+$args}]}
         -= {set leftvalue [expr {$leftvalue-$args}]}
         *= {set leftvalue [expr {$leftvalue*$args}]}
         /= {set leftvalue [expr {$leftvalue/$args}]}
         %= {set leftvalue [expr {$leftvalue%$args}]}
         =  {set leftvalue $args}
         default {error "invalid syntax : second argument is not an assignment"}
     }
     return $leftvalue
 }

See let.