TIP 672 and TIP 759 side by side

Eric T.’s page of $((...)) examples, taken up again with a third version of every example written in TIP 759 syntax, including tuple assignment (x, y, z) = $U. Every version was run, and the outputs shown are what came out.

plain TclTIP 672, $((expr))TIP 759, arithmetic syntax

This page was prepared by Claude (an AI assistant made by Anthropic) at Florent Merlet’s request. The plain-Tcl and TIP 672 code is Eric T.’s page as published, except the point_in_triangle helper of section 9, rewritten in every style without lassign. The TIP 759 versions are new, apart from section E of TIP 759 (in section 9 below), and owe several shortenings to Florent. The Calc module version of section 9 is not repeated here, since it was not re-run; see the original page for it.

How these were checked

Two builds of Tcl 9.0.5 were used.

Unless a section says otherwise, the outputs and the bytecode come from the prototype build. All the outputs are the same on both builds wherever the code runs on both.

The TIP 759 forms used here

[( expr )]
An expression inside a command, in place of [expr {expr}]. It can stand wherever a [...] can: a word, a quoted string, an array index.
{( ... )}
A script written in arithmetic syntax: a proc body, a foreach or lmap body. Its value is the value of its last statement.
a ; b
Statements in sequence.
name = expr
Assignment; the value of the statement is the value assigned.
(a, b, c)
A list.
(x, y) = $L
Tuple assignment: x and y receive the first two elements of $L, like lassign. Targets nest, ((x1, y1), (x2, y2)) = $edge; a missing element gives an empty string; extra elements are ignored. Prototype build only.
[cmd ...]
A Tcl command inside arithmetic syntax.
foreach ... ;
A raw command: some commands can be written without brackets inside arithmetic syntax, among them foreach, incr, llength, lindex, lset, lappend, lassign, return, if, while, for. The list is fixed in the current branch (lrepeat, set and list are not on it). A raw command ends at ;; a line break does not end it.
{(a) + (b)}
A body that begins with ( and ends with ), with balanced parentheses, is an arithmetic script: the two do not have to be a matching pair.

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))
}
TIP 759, with tuple assignment
proc cross759 {U V} {(
    (x, y, z) = $U; (u, v, w) = $V;
    $y*$w - $v*$z, $w*$x - $u*$z, $x*$v - $u*$y
)}

cross {1 2 3} {4 5 6} → -3 -6 -3 in all three.

The parentheses of the arithmetic body already make the last statement a list, so the three values need no parentheses of their own. Both vectors can also be taken apart in one statement, ((x,y,z),(u,v,w)) = ($U,$V);, at the cost of building the pair first (1.19 µs per call against 0.93 µs for the two assignments above, and 0.99 µs for plain Tcl). Without tuple assignment (the published 759 branch), the two lassign are written as raw commands inside the body: lassign $U x y z; lassign $V u v w;.

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))
TIP 759
[($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, all three give 80.0 40.0 120.0 60.0.

The comma list makes one substitution of four values, where 672 needs four substitutions inside a list command.

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}
TIP 759
proc dot759 {U V} {( s = 0; foreach u $U v $V {( s = $s + $u*$v )}; $s )}

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

foreach is a raw command: it needs no brackets inside the arithmetic body, and its own body is an arithmetic script too. The bytecode is the same with or without brackets (42 instructions).

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 the value needs a command around it)
proc tensor672 {U V} {lmap u $U {lmap v $V {set _ $(($u * $v))}}}
TIP 759 (an lmap body can be an arithmetic script)
proc tensor759 {U V} {lmap u $U {lmap v $V {( $u * $v )}}}

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

The value of an arithmetic script is its last expression, so 759 needs neither set _ nor expr here; it is the shortest of the three.

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
}
TIP 759
proc rot759 {deg} {(
    a = $deg/180.0*acos(-1);
    (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 all three.

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)))}
TIP 759
proc dist759 {x0 y0 x1 y1} {( hypot($x1-$x0, $y1-$y0) )}

# taking two points, with tuple assignment:
proc distPts759 {P Q} {( ((x0, y0), (x1, y1)) = ($P, $Q); hypot($x1-$x0, $y1-$y0) )}

dist 0 0 3 4 gives 5.0 in all three; distPts759 {0 0} {3 4} gives 5.0.

For a one-line numeric proc, plain expr and the arithmetic body are about the same length; 672 needs return.

7. Values inside strings, array indexes and conditions

TIP 672
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
TIP 759
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 where both proposals help most compared with [expr {...}]. [(...)] adds four characters around the expression and $((...)) adds five; [expr {...}] adds nine. The condition of if is already an expression, so it needs neither.

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
}
TIP 759
proc poly759 {c1 c2} {(
    out = [lrepeat [(llength $c1 + llength $c2 - 1)] 0];
    i = 0;
    foreach a $c1 {(
        j = 0;
        foreach b $c2 {
            lset out [($i+$j)] [(lindex $out [($i+$j)] + $a*$b)]
            incr j
        };
        incr i
    )};
    $out
)}

{2 4 3} times {3 2 4 5} gives 6 16 25 32 32 15 in all three.

The 759 version has an arithmetic body. llength, lindex, foreach and incr are raw commands, and llength $c1 + llength $c2 - 1 ends each llength at the operator. lrepeat is not on the list of raw commands yet, so it keeps its brackets. Every statement ends with ;, including the one after a loop: a line break does not end a raw command. The inner loop is left in command syntax; in arithmetic syntax ({( ...; j = $j + 1 )}) it works too, but runs slower (4.8 µs per call against 3.9 µs, and 4.0 µs for plain Tcl).

Size of examples 1 to 8

Characters of each proc, with every run of whitespace counted as one, and the number of $. The proc names are not counted.

exampleplain672759
1. cross product128 / 14 $116 / 17 $98 / 14 $
3. scalar product78 / 5 $74 / 6 $70 / 6 $
4. tensor product58 / 4 $62 / 5 $55 / 4 $
5. rotation matrix131 / 5 $111 / 10 $89 / 5 $
6. distance56 / 4 $61 / 5 $53 / 4 $
8. polynomial product224 / 11 $208 / 15 $202 / 12 $

672 adds one $ per expression. 759 adds none: [(...)] has no $, and the arithmetic body (examples 1, 5, 6) and the comma list replace the list commands. In examples 3 and 8 the $ count of 759 is one more than plain because the result is written $s (or $out) instead of set s.

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

This is the function from section E of TIP 759, which Eric’s page compares in several styles. Section E calls point_in_triangle, which TIP 759 does not define. Eric’s page wrote one in plain Tcl, with three lassign to take the points apart; neither lassign nor a tuple is needed there, since each point can go to sgn as two arguments with {*}. The helpers below are written that way, once in each style, and each edge function calls the helper of its own style, except section E, which keeps the plain helper it was published with.

helpers, 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} {
    set d1 [sgn $px $py {*}$t1 {*}$t2]
    set d2 [sgn $px $py {*}$t2 {*}$t3]
    set d3 [sgn $px $py {*}$t3 {*}$t1]
    expr {!((($d1 < 0) || ($d2 < 0) || ($d3 < 0)) && (($d1 > 0) || ($d2 > 0) || ($d3 > 0)))}
}
helpers, TIP 672
proc sgn672 {x1 y1 x2 y2 x3 y3} {
    return $((($x1-$x3)*($y2-$y3) - ($x2-$x3)*($y1-$y3)))
}

proc point_in_triangle672 {px py t1 t2 t3} {
    set d1 [sgn672 $px $py {*}$t1 {*}$t2]
    set d2 [sgn672 $px $py {*}$t2 {*}$t3]
    set d3 [sgn672 $px $py {*}$t3 {*}$t1]
    return $((!((($d1 < 0) || ($d2 < 0) || ($d3 < 0)) && (($d1 > 0) || ($d2 > 0) || ($d3 > 0)))))
}
helpers, TIP 759
proc sgn759 {x1 y1 x2 y2 x3 y3} {($x1-$x3)*($y2-$y3) - ($x2-$x3)*($y1-$y3)}

proc point_in_triangle759 {px py t1 t2 t3} {(
    d1 = [sgn759 $px $py {*}$t1 {*}$t2];
    d2 = [sgn759 $px $py {*}$t2 {*}$t3];
    d3 = [sgn759 $px $py {*}$t3 {*}$t1];
    !((($d1 < 0) || ($d2 < 0) || ($d3 < 0)) && (($d1 > 0) || ($d2 > 0) || ($d3 > 0)))
)}

sgn759 has no outer {( ... )}: its body begins with ( and ends with ), so it is already an arithmetic script. The three helpers agree with the lassign helper of Eric’s page on a grid of 36 points. The 759 helpers use no tuple, so they run on the published 759 branch too.

The edge function

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_triangle672 $px $py $t1 $t2 $t3] ? -$min_distance : $min_distance))
}
TIP 759, as published in section E
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 with tuple assignment
proc calculate_edge_distance_Tuple {px py t1 t2 t3} {(
    min_distance = 999999999;
    foreach edge [(($t1,$t2),($t2,$t3),($t3,$t1))] {(
        ((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) :;
    )};
    [point_in_triangle759 $px $py $t1 $t2 $t3] ? -$min_distance : $min_distance
)}

The tuple version makes three changes to section E. The three lassign become one nested tuple assignment, which takes an edge apart into its two points and their coordinates. The list of edges goes straight into foreach, so the edges variable is gone. foreach is written as a raw command, without brackets. The comment lines are also left out.

All four 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 2.0 for the point (2, 2) outside the triangle.

Size

The edge function only; the helpers are not counted, and the helper names are counted as point_in_triangle in every version.

plain672759 (section E)759 with tuples
non-comment lines15151611
$ characters35403532
characters, as printed591578724457
characters, comment lines removed591578663457
characters, each run of whitespace counted as one507494487401
characters, no whitespace at all424415404340

The counts were made again with a small script that uses the rules of Eric’s table: comment lines are removed before the last two rows are counted. It gives the same numbers as his table except in the whitespace-as-one row, where every version comes out one character higher. That row matters most, since Tcl needs the spaces between words.

The tuple version is the shortest by every measure: 401 characters against 487 for section E and 494 for 672. Most of the gain comes from the destructuring: one line instead of three lassign, and three fewer $.

The helpers, counted the same way (whitespace as one): plain 319, 672 329, 759 302 characters; 9, 9 and 7 non-comment lines; 26, 28 and 26 $. With {*} instead of lassign, the plain helper went from 379 to 319 characters.

Timing

One call of each edge function (inside point .5 .3), 20,000 calls per sample, median of 9 samples. The whole was repeated four times per run, in five runs, which gives 20 medians per row; the table shows the lowest. The machine was noisy during these runs: an empty compiled for loop took 28 to 47 ns per iteration, and the highest medians reached 8 to 9 µs in every row. The lowest median is the steadier figure, but the differences between rows are of the same size as the noise.

buildversionhelpersµs per call (lowest median)
759 branchplainplain5.19
759 branch759 (section E)plain5.34
prototypeplainplain5.51
prototype6726725.53
prototype759 (section E)plain5.45
prototype759 with tuples7595.66

These figures should not be compared with Eric’s page, which ran on a quieter, faster machine (about 20 ns per empty loop iteration); only the rows of this table compare with one another. On each build the versions are within about 4% of one another, and no version is clearly faster. The tuple version is the slowest by a small margin: a nested tuple assignment of one edge, ((x1, y1), (x2, y2)) = $e, takes 0.23 µs, against 0.16 µs for the three lassign it replaces. It took 0.42 µs before prototype v16j, which stopped building the list of names at run time. These numbers say nothing about large inputs or other functions.

10. Same bytecode

On the prototype build the three spellings of one assignment compile to the same instructions:

set A [expr {$y2-$y1}] · set A $(($y2-$y1)) · ( A = $y2-$y1 )
loadScalar1 %v0   # y2
loadScalar1 %v1   # y1
sub
storeScalar1 %v2  # A
done

The listings differ only in their command count: 2 for set A [expr ...], 1 for the 672 form, 0 for the arithmetic body. On the published 759 branch, an assignment in an arithmetic body is stored by name (storeStk); in the prototype it goes straight into the local variable slot (storeScalar), as plain Tcl does.

A tuple assignment is one instruction. (x, y) = $p in a proc compiles to:

push1 ""                 # placeholder: every name is a compiled local
loadScalar1 %v0          # p
push1 "{1 0} {2 1}"      # for each name: its slot, then its index path
tupleAssign

The literal tells tupleAssign where each value goes: {1 0} means “slot 1 receives element 0”, and a nested target such as ((x1, y1), (x2, y2)) gives paths {7 0 0} {8 0 1} {9 1 0} {10 1 1}. The instruction stores into the slots as storeScalar does, so traces, links (upvar, global) and typed variables behave as usual. A qualified name, written in braces ({::ns::x}), is stored by name instead.

Bytecode of the whole edge function

Each version is compared with plain Tcl on its own build; the counts come from tcl::unsupported::disassemble. The helpers are compiled separately and are not counted.

buildversioninstructionscommands compiledbytes of codestores by name
759 branchplain133223830
759 branch759 (section E)13853187
prototypeplain133223830
prototype672134183840
prototype759 (section E)12452950
prototype759 with tuples9021810

672 against plain: the same instructions in the same order, plus a second done that comes from the return, as on Eric’s 9.1.1 build.

759 (section E): on the published branch, 5 more instructions than plain, because 7 assignments are stored by name. On the prototype those 7 go into the local slots, and the function has 9 fewer instructions than plain, most of them startCommand (4 against 14).

759 with tuples: 43 fewer instructions than plain. The three lassign per edge (6 listIndexImm, 3 listRangeImm, 6 dup and their stores) become one tupleAssign, and the edges variable is gone. Writing foreach as a raw command changes nothing in the bytecode. Fewer instructions does not mean faster here: see the timing note in section 9.

The helpers (prototype build): point_in_triangle 81 instructions and 7 commands, the 672 one 82 and 7, the 759 one 78 and 3. All three sgn compile to the same 16 instructions. On the published branch, the 759 point_in_triangle stores its three assignments by name (81 instructions).

What these examples do not cover

TIP 759 adds more than a substitution: assignment, ;, the comma list and arithmetic scripts, all used above. Tuple assignment is not in the published TIP 759 branch; it comes from the TIP 764 prototype, which proposes it for TIP 759. As far as can be seen the two TIPs do not conflict: in the prototype build $((...)) and [(...)] work side by side, and the body of $((...)) is handed to the expression parser, so the TIP 759 extensions also work inside it. This was checked only with the examples on this page.