TIP 672 examples

What Tcl looks like with $((...)) (TIP 672)

These examples were generated by Claude (an AI assistant made by Anthropic) at Eric T.’s request. Florent asked for more examples than three, so that people can judge how $((...)) reads when it is used a lot. Eric did not want to edit the TIP 759 wiki page, so they are collected in this file instead. Claude wrote and ran the code; Eric asked for it and is sending it on.

The rule in one line. $((expr)) means exactly [expr {expr}]. It can be used wherever $ substitution works: a word, a quoted string, an array index, subst. Variables inside still need their own $, as in expr. (The TIP’s default spelling is $((...)); a build switch selects $(...) instead.)

How these were checked. Every plain-Tcl and $((...)) pair below was run by Claude on a build of the TIP 672 branch, and the outputs shown are what came out. For the one example written in TIP 759 syntax, Claude ran the code from section E of TIP 759 on a build of the tip-759b_tcl90 branch (check-in 6e5df9de10, Oct 13) and got the same number. The Calc-module version in section 9 was run with the module’s current GitHub version on the same 672 build and gives the same number.

Update, Oct 27. Florent published an updated comparison page (672-759.md, check-in 9c3a827c80) in which TIP 759 can call commands inside the arithmetic, so the TIP 759 edge function in section 9 is now his updated one and the character counts are redone. As he wrote it, that function did not run on Claude’s copy of the branch; with one change, parentheses around the if body, it did (see section 9). The Calc entry now uses the new list and tuple forms of the module, and the tables (characters, timing, bytecode) were measured again in one session, so the old and new rows can be compared.


1. Cross product

# plain Tcl
proc crossPlain {U V} {
    lassign $U x y z
    lassign $V u v w
    list [expr {$y*$w - $v*$z}] [expr {$w*$x - $u*$z}] [expr {$x*$v - $u*$y}]
}

# TIP 672
proc cross672 {U V} {
    lassign $U x y z
    lassign $V u v w
    list $(($y*$w - $v*$z)) $(($w*$x - $u*$z)) $(($x*$v - $u*$y))
}

cross {1 2 3} {4 5 6} gives -3 -6 -3 in both.

Honest note: the TIP 759 [( ... , ... , ... )] list form is more compact here than three separate $((...)) in a list. 672 does not have a list operator.

2. Rectangle from a centre, width and height (canvas coordinates)

# plain Tcl
list [expr {$Cx-$L/2.0}] [expr {$Cy-$H/2.0}] [expr {$Cx+$L/2.0}] [expr {$Cy+$H/2.0}]

# TIP 672
list $(($Cx-$L/2.0)) $(($Cy-$H/2.0)) $(($Cx+$L/2.0)) $(($Cy+$H/2.0))

With Cx=100, Cy=50, L=40, H=20 both give 80.0 40.0 120.0 60.0.

3. Scalar product (loop body)

# plain Tcl
proc dotPlain {U V} {set s 0; foreach u $U v $V {set s [expr {$s + $u*$v}]}; set s}

# TIP 672
proc dot672 {U V} {set s 0; foreach u $U v $V {set s $(($s + $u*$v))}; set s}

{1 2 3} and {4 5 6} give 32 in both.

4. Tensor product

# plain Tcl
proc tensorPlain {U V} {lmap u $U {lmap v $V {expr {$u * $v}}}}

# TIP 672 (an lmap body is a script, so it needs a command around the value)
proc tensor672 {U V} {lmap u $U {lmap v $V {set _ $(($u * $v))}}}

Both give {4 5 6} {8 10 12} {12 15 18}.

Honest note: here plain expr is shorter. A bare $((...)) is not a command, so in an lmap body it needs set _ or return in front of it.

5. Rotation matrix

# plain Tcl
proc rotPlain {deg} {
    set a [expr {$deg/180.0*acos(-1)}]
    list [expr {cos($a)}] [expr {sin($a)}] [expr {-sin($a)}] [expr {cos($a)}] 0 0
}

# TIP 672
proc rot672 {deg} {
    set a $(($deg/180.0*acos(-1)))
    list $((cos($a))) $((sin($a))) $((-sin($a))) $((cos($a))) 0 0
}

rot 90 gives 6.123233995736766e-17 1.0 -1.0 6.123233995736766e-17 0 0 in both.

6. Distance

# plain Tcl
proc distPlain {x0 y0 x1 y1} {expr {hypot($x1-$x0, $y1-$y0)}}

# TIP 672 (a proc body ends with a command, so it needs `return`)
proc dist672 {x0 y0 x1 y1} {return $((hypot($x1-$x0, $y1-$y0)))}

dist 0 0 3 4 gives 5.0 in both.

Honest note: for a one-line numeric proc, plain expr is simply shorter.

7. Values inside strings, array indexes and conditions

puts "area=$(($w*$h)) perimeter=$((2*($w+$h)))"      ;# area=21 perimeter=20
puts "array: $a($((1+1)))"                            ;# array: two
if {$(($w % 2)) == 1} {puts "w is odd"}               ;# w is odd
puts [format "%.2f" $((3.14159*$w*$w))]               ;# 153.94

This is the case where $((...)) is shortest compared with [expr {...}]: inside quoted strings and indexes.

8. Polynomial multiplication (inner loops, adapted from tcllib math)

# plain Tcl
proc polyPlain {c1 c2} {
    set out [lrepeat [expr {[llength $c1]+[llength $c2]-1}] 0]
    set i 0
    foreach a $c1 {
        set j 0
        foreach b $c2 {
            lset out [expr {$i+$j}] [expr {[lindex $out [expr {$i+$j}]] + $a*$b}]
            incr j
        }
        incr i
    }
    set out
}

# TIP 672
proc poly672 {c1 c2} {
    set out [lrepeat $(([llength $c1]+[llength $c2]-1)) 0]
    set i 0
    foreach a $c1 {
        set j 0
        foreach b $c2 {
            lset out $(($i+$j)) $(([lindex $out $(($i+$j))] + $a*$b))
            incr j
        }
        incr i
    }
    set out
}

{2 4 3} times {3 2 4 5} gives 6 16 25 32 32 15 in both. Nested $((...)) inside [...] inside $((...)) works.


9. A longer function: distance from a point to the edges of a triangle

This is the function from section E of TIP 759, so the styles can be compared side by side.

Two helpers that were not in the originals. Section E calls point_in_triangle but TIP 759 never defines it. Claude wrote the two small helpers below (a standard sign test of the point against the three edges) so that every version could actually be run. All the versions of the edge function call the same helper; only the way the helper is written differs.

Plain Tcl:

proc sgn {x1 y1 x2 y2 x3 y3} {
    expr {($x1-$x3)*($y2-$y3) - ($x2-$x3)*($y1-$y3)}
}

proc point_in_triangle {px py t1 t2 t3} {
    lassign $t1 ax ay
    lassign $t2 bx by
    lassign $t3 cx cy
    set d1 [sgn $px $py $ax $ay $bx $by]
    set d2 [sgn $px $py $bx $by $cx $cy]
    set d3 [sgn $px $py $cx $cy $ax $ay]
    expr {!((($d1 < 0) || ($d2 < 0) || ($d3 < 0)) && (($d1 > 0) || ($d2 > 0) || ($d3 > 0)))}
}

The same two helpers in the Calc style (see the Calc note below). All-numeric arguments let sgn and the three d values be written as plain function calls:

proc= sgn {x1 y1 x2 y2 x3 y3} {
    : (x1-x3)*(y2-y3) - (x2-x3)*(y1-y3)
}

proc= point_in_triangle {px py t1 t2 t3} {
    lassign $t1 ax ay
    lassign $t2 bx by
    lassign $t3 cx cy
    : {
        d1 = sgn(px, py, ax, ay, bx, by);
        d2 = sgn(px, py, bx, by, cx, cy);
        d3 = sgn(px, py, cx, cy, ax, ay);
        !(((d1 < 0) || (d2 < 0) || (d3 < 0)) && ((d1 > 0) || (d2 > 0) || (d3 > 0)))
    }
}

Plain Tcl

proc calculate_edge_distance_Plain {px py t1 t2 t3} {
    set edges [list [list $t1 $t2] [list $t2 $t3] [list $t3 $t1]]
    set min_distance 999999999
    foreach edge $edges {
        lassign $edge p1 p2
        lassign $p1 x1 y1
        lassign $p2 x2 y2
        set A [expr {$y2-$y1}]
        set B [expr {$x1-$x2}]
        set C [expr {$x2*$y1 - $x1*$y2}]
        set distance [expr {abs($A*$px + $B*$py + $C) / hypot($A, $B)}]
        if {$distance < $min_distance} {set min_distance $distance}
    }
    expr {[point_in_triangle $px $py $t1 $t2 $t3] ? -$min_distance : $min_distance}
}

TIP 672

proc calculate_edge_distance_672 {px py t1 t2 t3} {
    set edges [list [list $t1 $t2] [list $t2 $t3] [list $t3 $t1]]
    set min_distance 999999999
    foreach edge $edges {
        lassign $edge p1 p2
        lassign $p1 x1 y1
        lassign $p2 x2 y2
        set A $(($y2-$y1))
        set B $(($x1-$x2))
        set C $(($x2*$y1 - $x1*$y2))
        set distance $((abs($A*$px + $B*$py + $C) / hypot($A, $B)))
        if {$distance < $min_distance} {set min_distance $distance}
    }
    return $(([point_in_triangle $px $py $t1 $t2 $t3] ? -$min_distance : $min_distance))
}

TIP 759 (as published in section E, calculate_edge_distance_Arith; this is the version Claude ran)

proc calculate_edge_distance_Arith {px py t1 t2 t3} {(
       # Arithmetic Syntax
        edges = (($t1,$t2),($t2,$t3),($t3,$t1));
        min_distance = 999999999;
       [# Command Syntax
           foreach edge $edges {(
              # Arithmetic Syntax
              [ # Command Syntax
                 lassign $edge p1 p2
                 lassign $p1 x1 y1
                 lassign $p2 x2 y2      ] ;
              A = $y2-$y1; B = $x1-$x2;
              C = $x2*$y1 - $x1*$y2;
              distance = abs($A * $px + $B * $py + $C) / hypot($A, $B);
              $distance < $min_distance ? (min_distance = $distance) :;
         )}];
       [point_in_triangle $px $py $t1 $t2 $t3] ? -$min_distance : $min_distance
)}

TIP 759, updated version (with commands in expr), as given in Florent’s updated comparison page. As written it does not run on Claude’s copy of the tip-759b_tcl90 branch (check-in 6e5df9de10, Oct 13): the line if {$distance < $min_distance} {min_distance = $distance} fails with invalid command name "min_distance", because on that branch a braced body is arithmetic only if it begins with (, as the foreach body does. With one change, parentheses around the if body, {(min_distance = $distance)}, it runs: it gives the TIP’s number and is exactly equal to the plain version on 297 points (three triangles, 11 by 9 positions each). His newer branch may accept the line as written. The code below is as he wrote it, and the character counts are counted from this text (the parentheses add 2 characters).

proc calculate_edge_distance_Arith {px py t1 t2 t3} {(
        edges = (($t1,$t2),($t2,$t3),($t3,$t1));
        min_distance = 999999999;
        foreach edge $edges {(
            lassign $edge p1 p2
            lassign $p1 x1 y1
            lassign $p2 x2 y2;
            A = $y2-$y1;
            B = $x1-$x2;
            C = $x2*$y1 - $x1*$y2;
            distance = abs($A * $px + $B * $py + $C) / hypot($A, $B);
            if {$distance < $min_distance} {min_distance = $distance}
         )};
       [point_in_triangle $px $py $t1 $t2 $t3] ? -$min_distance : $min_distance
)}

Calc module (proc=; the edge function written in the Calc style, with the new list and tuple forms; the comment line shows the same line written with list)

proc= calculate_edge_distance_Calc {px py t1 t2 t3} {
    # the same line with list():  : edges = list(list(t1,t2), list(t2,t3), list(t3,t1))
    : edges = ((t1,t2),(t2,t3),(t3,t1))
    : min_distance = 999999999
    foreach edge $edges {
        : {
            ((x1,y1),(x2,y2)) = edge;
            A = y2-y1;
            B = x1-x2;
            C = x2*y1 - x1*y2;
            distance = abs(A*px + B*py + C) / hypot(A, B);
            distance < min_distance ? (min_distance = distance) : 0
        }
    }
    : point_in_triangle(px, py, t1, t2, t3) ? -min_distance : min_distance
}

What Calc is. It is a small module written in plain Tcl by Eric T. (on top of Colin Macleod’s prototype expression parser; https://github.com/rocketship88/colin-parser). It needs no change to Tcl. The command : takes an expression in which variables are bare names (no $) and which can call functions, including Tcl procs with numeric arguments, as in sgn(px, py, ...). proc= rewrites those expressions when the proc is defined, so they run as compiled code. Calc::transformProcs name ... does the same to procs that are already defined. Claude wrote the first Calc version of this function; Eric T. then changed it to use list(list(...)) for the edges and to call the helper as a function. On Oct 27 Claude added two forms to the module, after reading how TIP 759 writes lists and multiple assignment: a bare parenthesised comma list, (a, b, c), which builds a list (so ((t1,t2),(t2,t3),(t3,t1)) replaces list(list(t1,t2), ...)), and a tuple pattern on the left of =, ((x1,y1),(x2,y2)) = edge, which replaces the three lassign lines (edge -> ((x1,y1),(x2,y2)) is the same thing written left to right). They compile to the same instructions lassign uses. Both forms are in the current GitHub version of the module (the one the tuple version below needs); the helpers still use lassign and run with any version. The function and variable names match TIP 759’s, and it ends with a ? : expression, as TIP 759’s does, so there is no if or return. The current GitHub version of the module is needed for the long ||/&& line in the helper (a label clash when several &&/|| occurred in one proc was found while preparing this page and fixed in commit e07f433).

Limits. A Calc expression cannot contain [command] substitution, so a call to a Tcl command is written as a function call, as point_in_triangle(...) is here. A ? : needs both branches, so TIP 759’s cond ? (x = y) :; with nothing after the colon is written cond ? (x = y) : 0. Arrays are read-only in Calc, and Calc has no loop of its own, so the foreach is plain Tcl with a Calc block inside it.

The plain, 672, published-759 and Calc (list) versions give -0.14142135623730948 for .5 .3 {0.0 0.0} {1.0 0.0} {0.0 1.0}, the number published in TIP 759, and the plain, 672 and Calc versions all give 2.0 for a point outside the triangle (2 2). The updated 759 function, with the if body in parentheses, gives the same number and equals the plain version on all 297 points. The Calc (tuples) version was compared with the plain version on 297 points (three triangles, 11 by 9 positions each): all 297 results are exactly equal, on Tcl 9.1.1 (both spellings), 9.0.5 and 8.6.14. The Calc versions of the two helpers were also run under the plain and 672 edge functions, in place of the plain helpers, over 42 points with identical results, and the Calc helpers agree with the plain helpers on a grid of 36 points.

The edge function only (the helpers are not counted):

plain 672 759 (as published) 759 (updated) Calc (list) Calc (tuples)
non-comment lines 15 15 16 15 17 15
$ characters 35 40 35 35 4 1
characters, as printed (spaces, indentation and comments included) 591 578 724 582 557 585
characters, comment lines removed 591 578 663 582 557 497
characters, each separator counted as one (a run of whitespace, a line break, or , between arguments) 506 493 486 445 430 384
characters, no whitespace at all (a lower bound) 424 415 404 373 359 322

On size: the first character row counts everything printed, including the indentation and the comment lines (two in the published TIP 759 text, one in the Calc (tuples) code), which is why the published 759 looks longest there. In Tcl the spaces between words are required, so ignoring whitespace entirely is too generous; the row that counts each separator as one character keeps them (in Calc the argument separator is a comma, f(a, b), where Tcl uses a space, f a b, so , is counted as one character) (it also keeps a few spaces around operators that are optional). By that measure the updated TIP 759 is now clearly shorter than plain Tcl and 672 (445 against 506 and 493; the published version was 486), and Calc with tuples is the shortest (384). Florent’s page gives 340 for the updated function. That figure comes from string length [string map {{ } {}} [info body ...]]: it counts only the body, removes spaces but keeps the line breaks. With that method the updated function is 340 (the published one 408); with the no-whitespace row above, which counts the whole proc and removes all whitespace, it is 373 (the published one 404). The two numbers are not comparable with each other. With the two parentheses that make it run on Claude’s copy of the branch, the counts become 342 by his method and 375 by the no-whitespace row.

Eric T.’s notes on the Calc version. Before the tuple forms existed, the biggest cost for Calc was the word list, written four times in the edges line. He finds the list(list(...)) form easier to read anyway: among all the parentheses the word list shows where each list starts, and with no $ and small commas it is plainly three lists inside one list. The bare form, ((t1,t2),(t2,t3),(t3,t1)), is shorter (Calc (tuples) is now the shortest in every row except “as printed”, where its comment line is counted), but he does not think it is easier to read, so the code above keeps the list form in a comment line for comparison. Size is not the only thing that matters. The line count could also be reduced by putting : { on the same line as the first statement and the closing } at the end of the last one, but he prefers to keep those lines because the space helps to see the block, so they are left in.

Why Calc is in the tables. TIP 759 asks for new syntax for lists, multiple assignment and arithmetic scripts. The Calc rows are there to show that the list and tuple forms do not need a TIP: a module written in Tcl can provide them today, through tcl::unsupported::assemble, on Tcl 8.6 as well, and the code it generates is the same instruction sequence that lassign compiles to. That is also a reason to make assemble a supported command (Eric T.’s TIP 760). It does not replace the parts of 759 that need the core: the [( )], {( )} and "( )" forms and proc bodies that begin with ( change how Tcl parses a script, which a module cannot do.

On $: Florent is right that $((...)) adds $ characters. In this function it goes from 35 to 40, one for each expression turned into a substitution. Calc has the fewest $ (its variables are bare), at the price of a separate module and its own small language. Whether any of this looks worse is a matter of taste, as Florent says, and this is the real function so that others can judge.

Rough timing. Claude timed one call of each edge function (inside point .5 .3), 20,000 calls per sample, median of 9 samples, and repeated that four times. The figures are microseconds per call, as the lowest and highest of the four medians. This table was measured again on Oct 27, in one session on a slower machine than the first time, so it replaces the earlier figures and cannot be compared with them. The first four rows ran on the TIP 672 build (Tcl 9.1.1) and the next four on the tip-759b_tcl90 build (Tcl 9.0.5; the 759 row is the published version, since the updated one could not be run). The plain, 672 and 759 rows use the plain helpers; the Calc rows use the Calc helpers. Calibration: an empty compiled for loop runs at about 29 to 45 ns per iteration on 9.1.1, 28 to 41 ns on 9.0.5 and 24 ns on 8.6.14, so the machine was noisy and the builds are only roughly comparable; they are different Tcl versions and this is not a controlled benchmark.

build version µs per call
9.1.1 plain 5.22 – 5.38
9.1.1 672 5.07 – 5.66
9.1.1 Calc (list) 5.36 – 6.52
9.1.1 Calc (tuples) 5.10 – 6.49
9.0.5 plain 6.05 – 6.53
9.0.5 759 (published) 5.54 – 7.21
9.0.5 Calc (list) 5.11 – 5.62
9.0.5 Calc (tuples) 5.07 – 5.55
8.6.14 plain about 5.0 (best sample of 25)
8.6.14 Calc (list) about 5.2 (best sample of 25)
8.6.14 Calc (tuples) about 5.1 (best sample of 25)

Calc, being plain Tcl, was also run on Tcl 8.6.14 (64-bit, from the Ubuntu package), where TIP 672 and TIP 759 do not exist: the page’s Calc code gives the same results there, and the module’s own test file (calc.test, 173 tests) passes with 0 failures, with the tuple forms added. The two 8.6 rows are the best single sample of 25 and are only a rough guide. 8.6 itself is slower than 9.x in the earlier session, so those rows should not be compared with the others.

The updated 759 function (with the if body in parentheses) was timed on the 9.0.5 build too, in two separate runs: 5.26 – 7.21 and 5.87 – 6.68 µs. The machine was too noisy in the last run to make a reliable table row of it (the same Calc function ranged from 5.1 to 8.9 µs between runs), so it is not in the table; it was no different from the published version.

On each of the 9.x builds the ranges of the versions overlap, which is about the size of the run-to-run noise on this machine, so no version is clearly faster. These numbers say nothing about large inputs or other functions.


10. Same bytecode

set A [expr {$y2-$y1}] and set A $(($y2-$y1)) compile to the same instructions:

loadScalar %v0   # y2
loadScalar %v1   # y1
sub
storeScalar %v2  # A
done

(The only difference in the disassemble listing is a label line.) This is because $((...)) is parsed once as the argument of a braced expr, and the existing compiler does the rest.

The Calc versions were disassembled too. A Calc-compiled sgn gives the same instruction listing as the plain sgn, once addresses and source text are removed. The Calc point_in_triangle is the same except in its &&/|| part: the module writes those out as its own jump sequences, so its listing is 139 lines against 129 for plain Tcl, about 8% longer. The three lassign lines and the calls to sgn are the same, apart from the name being written ::sgn and Calc not emitting the per-command bookkeeping instruction.


Bytecode of the whole edge function

Claude disassembled calculate_edge_distance_Plain, _672, both _Calc versions and TIP 759’s published _Arith (each calling the plain helpers, except the Calc ones, which call the Calc helpers). The first rows were measured again on Oct 27 with the same method and give the same numbers as before. Counts are only comparable within one build, since the 9.1.1 and 9.0.5 builds encode some instructions differently, so each version is compared with plain Tcl on its own build.

build version instructions commands compiled bytes of code
9.1.1 plain 133 22 569
9.1.1 672 134 18 570
9.1.1 Calc (list) 123 12 491
9.1.1 Calc (tuples) 111 9 415
9.0.5 plain 133 22 383
9.0.5 759 (published) 138 5 318
9.0.5 759 (updated, with the if body in parentheses) 138 6 325
9.0.5 Calc (tuples) 111 9 244

The bytes row says little about speed: it mostly reflects how many startCommand instructions (9 bytes each) a version needs.

11. Spelling and compatibility notes

The shorter spelling. The TIP’s default spelling is $((expression)); a build switch selects $(expression). The TIP’s Migration section says that a script written with $((expression)) keeps working with the same value if Tcl later changes to $(expression), because that spelling reads $((expression)) as $( followed by a parenthesised expression. So every $((...)) above can later become the shorter $(...), for example $(($y2-$y1)) becomes $($y2-$y1), once the one incompatibility the TIP names has been dealt with: code that uses $(index), the array with the empty name, would have to change to the set command. Nothing else in these examples would change.

Compatibility in general. Any new syntax costs something. TIP 759’s own Incompatibilities section says that a proc named ( would be shadowed by its shorthand, and gives a backslash as the workaround. That is a small cost, and it is listed here only to show that both proposals have one (the TIP 672 one is described above); the page does not weigh them against each other. TIP 759 draft 2.2, as read on Oct 27; it may have changed since.

What these examples do not cover

TIP 759 adds more than a substitution: assignment, ;, the comma list, arithmetic scripts and commands inside expr. 672 adds none of those, so no 672 versions of them were written. As far as can be seen the two ideas don’t conflict: the body of $((...)) is handed to expr, so extensions to the expr language should be usable inside it too (this was not tried, since expr doesn’t have them). The same goes for the commands-in-expr feature of the updated 759: a raw lassign or lindex inside the arithmetic has no 672 counterpart, because $((...)) hands its body to expr, which does not have it.