Variables and math

Each value in Tcl is a string. A command that needs a number reads the string as a number. This lesson gives jot a count of its notes, and shows the math traps that an agent puts in code.

Variables

set with two words gives a value to a variable. set with one word gives the value back: set note. A variable that has no value is an error: set count. info exists count checks first.

incr adds to an integer, and makes the variable with 0 first when it has no value. incr count counts the first note. incr count 2 adds 2, and incr count -1 takes 1 away. append adds text: append note " and eggs".

Math with expr

expr computes an expression. It has the operators of C, ** for a power, and functions such as abs, round, and max. expr {$count * 10} uses the variable. Integers have no fixed size: expr {2 ** 64}.

The type of the result comes from the operands. An integer divided by an integer is an integer: expr {7 / 2}. One float operand makes a float: expr {7 / 2.0}. Integer division rounds down, also for a negative number: expr {-7 / 2}. In C and in Go the result is -3.

A string that is a number works as a number: expr {"10" + 1}. Another string is an error: expr {"ten" + 1}.

Compare numbers and strings

== compares two numbers when both are numbers: expr {"1.0" == "1"}. eq compares the text: expr {"1.0" eq "1"}. Use eq and ne for strings. == on two strings that look like numbers gives a number comparison.

Reading code an agent wrote

Ask an agent

Write a Tcl proc that gives the average of a list of numbers as a float. Put each expr in braces.

Check that the answer divides by a float or uses double(), and that an empty list gives an error with a clear message.

Try this

The state of the shell at the start of this lesson
set note "buy milk"