mathematical set

4 Jan 2006 - Googie - Here's some very simple way to use set command like the following:

 set a 5
 set b $a + 3 + ($a * 2)
 puts $b

'$b' will be 18. The only requirement is to use 'mathematical' set case with more than 1 and 2 arguments (which are number of arguments for default set syntax). In practise it means that you have to do at least one white-space in math expression, or set will be interpreted as the Tcl-built-in one. Here's code to enable such functionality:

 rename ::set ::set.org
 proc ::set {var args} {
     if {[llength $args] > 1} {
         uplevel [list ::set.org $var [eval expr "{$args}"]]
     } else {
         uplevel [list ::set.org $var [lindex $args 0]]
     }
 }

RS: Cute. But the case of [llength $args]==0 should also be covered as returning the value - right now it would set it to {}. Also, all the efficiency gained with braced expressions is of course lost here...


WHD: I prefer "let", as in

 let b {$a + 3 + ($a * 2)}

or especially

 let x {$x + 1.5}

Implemented in C, it's also reasonably fast.

escargo 10 Jan 2006 - I kind of like that distinction (that is, between set and let). (Maybe because I was exposed to some form of BASIC in ancient times.) It certainly is less typing to write

 let x {$x + 1.5}

than

 set x [expr {$x + 1.5}]

What about allowing bare words to dispense with the $? (Since the braced expression is a right hand side, after all.) That would give

 let x {x + 1.5}

Is that too radical a change?

RS: It might cause conflicts between functions and arrays:

 let x {sin(x)+cos(y)}

Lars H: IMO, it wouldn't be onerous to continue to require $ for arrays.

 let r {$A(i) + cos(omega*j)}

Perhaps also some shorthand for lindex while we're at it? I think # is unused.


RS takes this cue to let unknown know:^)

 % know {if {[lindex $args 1] eq "#"} {return [lindex [lindex $args 0] [lindex $args 2]]}}

 % {hello world out there} # 2
 out
 % set test {1 2 3 4 5 6 7}
 1 2 3 4 5 6 7
 % set t [$test # 4]
 5

NEM likes adding a touch more sugar and having:

 let x = {$x + 1.5}

escargo 11 Jan 2006 - One of the reasons I like plain let instead of set is because it is shorthand. Having the = adds more characters, which is the opposite of the goal of shorthand. You could go farther down this path and do

 = x {x + 1.5}

as a somewhat more radical version. It's even shorter. I still prefer let, though.