XPS-Q8
Tcl Manual
of many math functions supported by the
expr
command. The variable
c
is local to
the procedure; it is defined only during execution of
Diag
. Variable scope is discussed
further in Section 7. It is not really necessary to use the variable
c
in this example. The
procedure can also be written as:
proc
Diag {a b} {
return
[
expr
sqrt
($a * $a + $b * $b)]
}
The
return
command is used to return the result of the procedure. The return
command
is optional in this example because the Tcl interpreter returns the value of
the last command in the body as the value of the procedure. So, the procedure could be
reduced to:
proc
Diag {a b} {
expr
sqrt
($a * $a + $b * $b)
}
Note the use of curly braces in the example. The curly brace at the end of the first line
starts the third argument to
proc
, which is the command body. In this case, the Tcl
interpreter sees the opening left brace, causing it to ignore newline characters and scan
the text until a matching right brace is found.
Double quotes have the same
property
. They group characters, including
newlines, until another double quote is found. The result of the grouping is such that the
third argument to
proc
is a sequence of commands. When they are evaluated later, the
embedded newlines will terminate each command.
The other crucial effect of placing the curly braces around the procedure body is to
delay any substitutions in the body, until the procedure is called. For example, the
variables
a
,
b
, and
c
are not defined until the procedure is called, so we do not want to
do variable substitution at the time
Diag
is defined.
The
proc
command supports additional features such as having a variable number of
arguments and default values for arguments.
2.2.8
A Factorial Example
To reinforce what we have learned thus far, see the example below which uses a
while
loop to compute the factorial function:
Example 1–13: A
while
loop to compute a factorial.
proc
Factorial {x} {
set
i
1
;
set
product 1
while
{$i <= $x} {
set
product [
expr
$product * $i]
incr
i
}
return
$product
}
Factorial
10
⇒
3628800
The
semicolon
used on the second line is there to remind you that it is a command
terminator, just like the newline character. The
while
loop is used to multiply all
numbers from one to the value of
x
. The first argument to
while
is a boolean
expression, and the second argument is the command body to be executed.
The same math expression evaluator used by the
expr
command is used by
while
to evaluate the boolean expression. There is no need to explicitly use the
expr
command in the first argument to
while
, even if you have a much more complex
expression.
The loop body and the procedure body are grouped with curly braces in the same way.
The opening curly brace must be on the same line as
proc
and
while
. If you want to
EDH0307En1041 — 10/17
8