Version 10 of Tcl in comparison

Updated 2002-12-16 17:21:28

Richard Suchenwirth 2002-12-16 - For people experienced in other languages, it may be interesting to compare code snippets between Tcl and other languages, to demonstrate similarities and differences. Please add more from your experience!

C

 void countdown(int n) {         | proc countdown {n} {
    int i;                       |
    for(i=n; i>0; i--) {         |    for {set i $n} {$i>0} {incr i -1} {
       printf("%d...\n", i);     |        puts $i...
    }                            |    }
 }                               | }
  • Everything is a command in Tcl. Function definitions are done with the proc command, assignments with the set command, in/decrementation of integers with the incr command.
  • Retrieving the value of a variable goes with prefixed $ sign - while mentioning the name of a variable it is not used
  • Variable type rarely matters and is not declared. Only incr would complain if its first argument is not an integer
  • Formatting values into strings goes in simple cases by straight string concatenation like in $i.... for stronger control, format is comparable to sprintf
  • puts, unlike printf(), needs no explicit newline.

Scheme

 (define foo 42)                 | set foo 42
 (define (square x) (* x x))     | proc square x {expr $x * $x}
 (define bar (square foo))       | set bar [square $foo]
 (define grill '(square foo))    | set grill {square $foo}
  • Functions are also defined with the proc command. Their result is the last executed command in the body
  • Arithmetics is not done with prefix functions, but Infix-style like in C, in the argument(s) to the expr command
  • set is used for variables, proc for functions - no unified define in Tcl (except if you write one - see the Scheme page ;-)
  • Tcl commands on toplevel are not enclosed in parens. Embedded commands like the first call to square go into brackets for eager evaluation; the equivalent to quoting is curly braces around a string
 (define (abs x)                 | proc abs x {
   (cond ((> x 0) x)             |    expr { $x > 0?  $x :
         ((= x 0) 0)             |           $x == 0? 0 :
         ((< x 0) (- x))))       |           $x < 0?  -$x}
                                 | }
                                 | or: proc abs x {expr abs($x)}
  • expr can, with the ?: operator, operate like cond
  • It also has built-in math functions that can be exported in a one-liner as shown (Importing expr functions)
  • Tcl needs less parens (which often amount to braces or brackets)

Tcl and other languages


See also Pleac and http://www.merd.net/pixel/language-study/scripting-language/