\documentclass[]{article}
\usepackage{amsmath,graphicx,supertabular,hyperref,tabularx,ifthen}
\title{TIP \#215: Make [incr] Auto-Initialize Undefined Variables}
\date{August 25, 2004}
\author{Andreas Leitgeb, Don Porter}
\urlstyle{sf}
\setlength{\parskip}{1ex}
\setlength{\parindent}{0pt}
\def\tipversion$#1${\texttt{\$#1\$}}
\def\tiplangle#1{\ensuremath{<}}
\def\tiprangle#1{\ensuremath{>}}
\def\tipbar#1{\ensuremath{|}}
\def\tipmail#1#2{\(\langle\){\small\expandafter\url{#1@#2}}\(\rangle\)}
\ifx\pdfoutput\undefined
\newcommand{\tipimage}[2]{\typeout{Make sure you download #1.eps}\ifthenelse{\lengthtest{0.8\textwidth>#2}\and\lengthtest{0pt<#2}}{\includegraphics{#1.eps}}{\includegraphics[width=0.8\textwidth]{#1.eps}}}
\newcommand{\tipxref}[1]{}
\newcommand{\tipxrefend}{}
\else
\newcommand{\tipimage}[2]{\typeout{Make sure you create #1.pdf}\ifthenelse{\lengthtest{0.8\textwidth>#2}\and\lengthtest{0pt<#2}}{\includegraphics{#1.pdf}}{\includegraphics[width=0.8\textwidth]{#1.pdf}}}
\pdfcatalog{/PageMode /UseOutlines}
\newcommand{\tipxref}[1]{\pdfannotlink attr {/C [0.5 0.5 1.0] /Border [0 0 1]} goto name {#1}}
\newcommand{\tipxrefend}{\pdfendlink}
\fi
\newenvironment{tipabstract}{\begin{abstract}}{\end{abstract}}
\begin{document}\maketitle
\begin{center}\begin{tabularx}{\linewidth}{|r@{: }X|}\hline
\textbf{TIP \#215}&\textbf{Make [incr] Auto-Initialize Undefined Variables}\\\hline
Author&

Andreas Leitgeb \tipmail{avl}{logic.at}
\par
Don Porter \tipmail{dgp}{users.sf.net}
\\
Created&Wednesday, \(\text{25}^{\text{th}}\) August 2004\\
Type&Project\\
Tcl Version&\(8.5\)\\
State&Final\\
Vote&Done\\
Version&\tipversion$Revision: 1.11 $\\
Keywords&Tcl\\
Post History&\\
\hline\end{tabularx}\end{center}
\thispagestyle{empty}\pagestyle{empty}
\begin{tipabstract}

Unlike \textbf{append} and \textbf{lappend}, \textbf{incr} currently does not auto-create yet-undefined variables. This TIP proposes to make \textbf{incr}'s behaviour in this regard more like the aforementioned commands.
\end{tipabstract}
\tableofcontents\setcounter{page}{0}\clearpage\pagestyle{plain}

\section{Rationale}

A quite common task is counting the number of occurrences of items in a given list. The usual solution is to iterate the list, and for each item, increment the associated value in a tcl-array. As of now this requires a separate step of determining the not-yet-existence and eventual initialization to 0 or alternatively \textbf{catch}'ing errors from \textbf{incr} and setting the variable, if an error was raised.

If we instead alter \textbf{incr} to treat non-existant variables as if they contained the value 0, this would be more like the auto-initializing behaviour of \textbf{append} and \textbf{lappend}, and would make writing code that does this sort of summing up much easier. It is also very similar to the way that the \textbf{dict incr} subcommand operates.

\section{No Change for Variables that Contain Non-Integers}

Just as \textbf{lappend} does complain if passed a variable whose value is an invalid list (e.g. a single open-brace), so it appears reasonable for \textbf{incr} to still throw an error if the variable contains something that is not a number.

The empty string is invalid as an operand for \textbf{expr}'s integer operators, so it should remain illegal to \textbf{incr} an existing variable that contains an empty string.

\section{Further Special Cases}

If a variable passed to incr is not yet existing, but linked to some other not-yet existing var, or if it is traced, then of course it would add flesh to that existing husk. Care should be taken that any write traces only trigger once (like for \textbf{lappend}), not twice (as in: for initializing and then for incrementing).

\section{Proposal}

The current \textbf{incr} command behaves like the following proc:
\begingroup\small\begin{verbatim}
 proc incr {varName {increment 1}} {
     upvar 1 $varName v
     return [set v [expr {$v + $increment}]] ;# read/write trace
 }  
\end{verbatim}
\endgroup

It is proposed to make \textbf{incr} behave like the following modified proc:
\begingroup\small\begin{verbatim}
 proc incr {varName {increment 1}} {
     upvar 1 $varName v
     set code [catch {set v} value] ;# read trace
     if {$code} {
         return [set v $increment]  ;# write trace
     }
     return [set v [expr {$value + $increment}]] ;# write trace
 }  
\end{verbatim}
\endgroup

Please note these example procs are meant to illustrate the proposed change only. They do not fully reflect the exact function of \textbf{incr} (limiting to only integer values, for example).

For a more concrete illustration of the proposal, see the reference implementation, SF patch \#1413115 [\url{http://sourceforge.net/tracker/index.php?func=detail&aid=1413115&group_id=10894&atid=310894}].

\section{Discussion}

There have been comments that \textbf{incr} modified as proposed would lose one means of typo-detection: If the varname is mistyped, then instead of throwing an error, it would turn into a noop.

My (TIP-originator) answer to this: relying on thrown exceptions for mistyped varnames is a very weak strategy in dynamic (non-compiled) languages like tcl, anyway, because it would require a 100\%-test-coverage of execution-paths.

Nevertheless, this shouldn't exclude discussion about less typo-forgiving alternatives:

Proposed (by others) alternative \#1: make \textbf{incr} accept a second optional argument \textit{init} which, if specified, will cause \textbf{incr} to accept non-existent variables and initialize them with the value \textit{init}. One disadvantage of this behaviour is, that it is at odds with append and lappend behaviour, which would rather imply that if more than one argument is given after the varname, then each of them would be added in row. Another con would be, that it would not be intuitive, whether the resulting value would be \textit{init} or (\textit{init} + \textit{increment}). Similar alternatives mentioning new option \textbf{-initValue} are over-verbose imho.

Another way to partially reduce this proposal's forgiveness would be to allow autoinitialization only for array-elements. This looks grossly unorthogonal at first sight, but addresses the fact, that the primary reason for TIP 215 was counting occurrences of strings, which are then made keys in an array. The danger of mistyped array-keys is surely much lower than that of mistyped variable names. See \cite{tip224}

\section{Copyright}

This document has been placed in the public domain.

\section{Colophon}

\textit{TIP AutoGenerator --- written by Donal K. Fellows}
\begin{thebibliography}{TIP \#1}
\addcontentsline{toc}{section}{References}
\bibitem[TIP \#224]{tip224}
Peter MacDonald,
Robert Seeger,
\emph{Add New [array] Subcommands 'incr' and 'value'},
on-line at \url{http://purl.org/tcl/tip/224.html}
\end{thebibliography}
\end{document}
