Saturday, February 05, 2011

NedNews: Background

The main idea behind Tcl is "everything is a string". Code is a series of strings evaluated in a particular context. Lists are strings formatted in a particular way. (There are also maps from string to string)

This might seem stupid or limiting, but it actually flattens interfaces - now you don't need to worry as much about how to interface different components.

You have production and consumption of strings (somewhat like command pipelines in Unix).

Tcl looks enough like C that it can be misleading:

for {set i 0} {$i <= 10} {incr i} {
puts "Hello $i"
}

It can be more helpful at times to actually think of it as a stripped down Lisp-like:

(for, (set, i, 0), (<=, $i, 10), (incr, i) (puts, "Hello $i"))
(which makes more sense if you are used to Lisp, else little sense)
  • The first command on each line in Tcl doesn't need parens (and the whole program doesn't need parens).
  • Arguments are separated by whitespace instead of commas. Double quotes surround arguments which contain white space.
  • Curly braces are used to protect strings from variable substitution (when variables will get substituted later).
  • Square brackets enclose nested commands (arguments which need to be evaluated as function calls)
  • New lines are significant, for is really a procedure which takes the body as an argument - lambda programming from the beginning!
That last point means:

for {set i 0} {$i <= 10} {incr i}
{
puts "Hello $i"
}

won't work (for will fail to find its body argument).

In other words, the Tcl parser is very simple. It processes one line at a time (concatenating lines inside curlies or that end in "\"). It then breaks the line up into "words" based on spaces and tabs. The first word is used as the command, and the other words get passed along as arguments. Substitution is done to all words, except inside of of curly braces ("{}"). Square braces ("[]") trigger nested execution. That's it!

Let's say you want to display the results of some math:

puts "Two plus two = [expr 2 + 2]"


Again, in Lisp, this is:

(puts, "Two plus two (expr, 2, +, 2)")
(assuming Lisp would expand inside quotes, which I don't think it does)

The brackets trigger execution inside the currently executing line of code. The first word is the command ("mathematical EXPRession"). expr takes any number of word arguments, which get evaluated as math.

2 + 2 can't work because "2" is not a command. Some people create commands for "+,-,/,*" - then you can do "+ 2 2". That is good for RPN people, but I don't see the benefit.

No comments: