'\"
'\" Copyright (c) 2004 Salvatore Sanfilippo.  All rights reserved.
'\"
'\" See the file "license.terms" for information on usage and redistribution
'\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
'\" 
'\" RCS: @(#) $Id: $
'\" 
.so man.macros
.TH range n "" Tcl "Tcl Built-In Commands"
.BS
'\" Note:  do not modify the .SH NAME line immediately below!
.SH NAME
range \- Create lists containing arithmetic progressions
.SH SYNOPSIS
\fBrange \fIstart end step
.br
\fBrange \fIstart end
.br
\fBrange \fIend
.BE

.SH DESCRIPTION
.PP
This command creates a list containing an arithmetic progression.
The arguments must be integers. When the command is called with
three arguments, it returns a list of integers where the \fIi\fR-th
element of the list is \fIstart+i*step\fR. If \fIstep\fR is positive
the last element of the returned list is the largest element
\fIstart+i*step\fR less than \fIend\fR. If \fIstep\fR is negative
the last element of the returned list is the smallest element
\fIstart+i*step\fR greater then \fIend\fR. The command returns
the empty list if \fIstart\fR and \fIend\fR have the same value.
An error is returned if the resulting list is of infinite length
or if \fIstep\fR is zero.

This command can be called with two arguments, omitting the
value of \fIstep\fR that will default to \fB1\fR. It's also
possible to call \fBrange\fR with just one argument, omitting
the value of \fIstart\fR that will default to \fB0\fR and
\fIstep\fR that will default to \fB1\fR.

The \fBrange\fR command is implemented in a way that makes
it possible to store the generated lists in constant space
under certain conditions, regardless of the actual value of
\fIstart\fR, \fIend\fR, and \fIstep\fR. Accessing the resulting
list only using the commands \fBforeach\fR, \fBlindex\fR and \fBllength\fR
should allow the user to take advantage of this optimization.
The optimization is transparent to the user, so \fBrange\fR returns
true Tcl lists under every practical aspect.
.SH EXAMPLE
Some example of output.
.CS
% range 10
0 1 2 3 4 5 6 7 8 9
% range 5 30 5
5 10 15 20 25
% range 10 0 -2
10 8 6 4 2
% range 8 -2 -3
8 5 2 -1
% llength [range 5 5] 
0
.CE

Using \fBrange\fR and \fBforeach\fR as alternative to \fBfor\fR.
.CS
% set total 0
0
% foreach x [range 10] {incr total $x}
% set total
45
.CE

Using \fBrange\fR and \fBexpr\fR to compute the factorial function.
.CS
% expr [join [range 5 1 -1] *]
120
.CE

Using \fBrange\fR with an helper \fBmap\fR function that maps
a Tcl script to a list to generate the square of the first ten
natural numbers.
.CS
% proc map {varname script mylist} {
>    upvar $varname var
>    set res {}
>    foreach var $mylist {
>        lappend res [uplevel 1 $script]
>    }
>    return $res
>}
% map x {expr {$x*$x}} [range 0 10]
0 1 4 9 16 25 36 49 64 81
.CE

.SH "SEE ALSO"
for(n), list(n), lindex(n), linsert(n), llength(n), 
.VS 8.4
lset(n)
.VE
lsort(n), lrange(n)

.SH KEYWORDS
arithmetic progression, range, iteration, looping
