\documentclass[]{article}
\usepackage{amsmath,graphicx,supertabular,hyperref,tabularx,ifthen}
\title{TIP \#174: Math Operators as Commands}
\date{March 15, 2004}
\author{Kristoffer Lawson, Donal K. Fellows, David S. Cargo, Peter Spjuth, Kevin B. Kenny}
\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 \#174}&\textbf{Math Operators as Commands}\\\hline
Author&

Kristoffer Lawson \tipmail{setok}{altparty.org}
\par
Donal K. Fellows \tipmail{donal.k.fellows}{man.ac.uk}
\par
David S. Cargo \tipmail{escargo}{skypoint.com}
\par
Peter Spjuth \tipmail{peter.spjuth}{space.se}
\par
Kevin B. Kenny \tipmail{kennykb}{acm.org}
\\
Created&Monday, \(\text{15}^{\text{th}}\) March 2004\\
Type&Project\\
Tcl Version&\(8.5\)\\
State&Final\\
Vote&Done\\
Version&\tipversion$Revision: 1.21 $\\
Post History&\\
\hline\end{tabularx}\end{center}
\thispagestyle{empty}\pagestyle{empty}
\begin{tipabstract}

This TIP describes a proposal for math operators in Tcl as separate commands, acting much like the equivalent in the Lisp language. This would make simple usage of mathematics much clearer.
\end{tipabstract}
\tableofcontents\setcounter{page}{0}\clearpage\pagestyle{plain}

\section{Rationale}

While the \textbf{expr} command works fairly well for longer mathematical expressions, it is extremely tedious for the most common uses, such as handling indices. Take the following examples:
\begingroup\small\begin{verbatim}
 set newList [lrange $list [expr {$idx - 5}] [expr {$idx + 5}]]
 .c create oval [expr {$x - $r}] [expr {$y - $r}] [expr {$x + $r}] [expr {$y + $r}]
\end{verbatim}
\endgroup

Many find this particular aspect of Tcl unappealing. It gets increasingly difficult to read as more and more simple mathematical expressions build up. (See \textit{Example} below for how these will look after the proposed change.)

\section{Proposed Change}
\begin{enumerate}
\item{}
A group of Tcl commands are added which would handle mathematical operations without the need to use \textbf{expr}. Most commands would take a variable amount of arguments and would work such that the operator is applied to the combination of the first and second arguments. The result of this combination is then used with the operator for the third argument, etc. If only one argument is given, it is returned as is. See below for details for each operator. An example implementation of the \textbf{+} command in Tcl follows:
\begingroup\small\begin{verbatim}
 proc ::tcl::mathop::+ {args} {
     set r 0
     foreach operand $args {
         set r [expr {$r + $operand}]
     }
     return $r
 }
\end{verbatim}
\endgroup
\setcounter{enumi}{1}
\item{}
All operator commands will be kept in the \textbf{::tcl::mathop} (in line with \textit{::tcl::mathfunc} from \cite{tip232}) namespace, from which they would most commonly be imported into the calling namespace (or resolved in it by means of the \textbf{namespace path} (\cite{tip229}) command).
\setcounter{enumi}{2}
\item{}
The commands are not connected to their corresponding \textbf{expr} operator. Overloading or adding any command in \textbf{::tcl::mathop} does \textit{not} affect operators in \textbf{expr} or any other command that calls \textit{Tcl\_ExprObj}, and nor does overriding \textbf{expr} alter the behaviour of any command in \textbf{:::tcl::mathop}.
\end{enumerate}

\subsection{Operator Commands Details}

Unary operators \textbf{\~{}} and \textbf{!} always take one argument.
\begingroup\small\begin{verbatim}
Op/argc  0    1   2   3+
~       err  ~a  err  err
!       err  !a  err  err
\end{verbatim}
\endgroup

Left-associative operators that naturally allow 0 or more arguments do so:
\begingroup\small\begin{verbatim}
Op/argc  0   1   2     3+
+        0   a   a+b   a+b+c...
*        1   a   a*b   a*b*c...
&       -1   a   a&b   a&b&c...
^        0   a   a^b   a^b^c...
|        0   a   a|b   a|b|c...
\end{verbatim}
\endgroup

Other left or right associative operators. Operator \textbf{**} is right associative, which needs to be noted clearly.
\begingroup\small\begin{verbatim}
Op/argc  0   1   2     3+
**       1   a   a**b  a**(b**(c...))
\end{verbatim}
\endgroup

(This behaviour depends on the eventual modification of the \textbf{**} operator in [expr] to have right-associativity, which is the subject of \cite{tip274}. If TIP \#274 fails, \textbf{**} should be left- or non-associative.)

Nonassociative operators (including the list operators, ``\textbf{in}'' and ``\textbf{ni}'') must always be binary.
\begingroup\small\begin{verbatim}
Op/argc   0    1    2      3+
<<       err  err  a<<b    err
>>       err  err  a>>b    err
%        err  err  a%b     err
!=       err  err  a!=b    err
ne       err  err  a ne b  err
in       err  err  a in b  err
ni       err  err  a ni b  err
\end{verbatim}
\endgroup

Subtract and divide treat their arguments in a left-associative way \textit{except} for in the unary case. Unary minus is negation, and unary divide is reciprocal.
\begingroup\small\begin{verbatim}
Op/argc  0    1      2    3-
-       err  -a     a-b  ((a-b)-c)...
/       err  1.0/a  a/b  ((a/b)/c)...
\end{verbatim}
\endgroup

Comparison operators other than \textbf{!=} and \textbf{ne} test for ordering:
\begingroup\small\begin{verbatim}
Op/argc  0  1   2       3+
<        1  1  a<b     ((a<b)&(b<c)&...)
<=       1  1  a<=b    ((a<=b)&(b<=c)&...)
>        1  1  a>b     ((a>b)&(b>c)&...)
>=       1  1  a>=b    ((a>=b)&(b>=c)&...)
==       1  1  a==b    ((a==b)&(b==c)&...)
eq       1  1  a eq b  ((a eq b)&(b eq c)&...)
\end{verbatim}
\endgroup

(Note the single \textbf{\&}; a Tcl command is not capable of ``short circuit'' evaluation of its arguments.)

The operators that do conditional evaluation of their arguments (\&\&, \tipbar{}\tipbar{} and ?:) are not included. This is because their characteristic evaluation laziness is best modelled using the existing \textbf{if} command.

\subsection{Example}

As an example use, let us change the lines from above:
\begingroup\small\begin{verbatim}
 set newList [lrange $list [- $idx 5] [+ $idx 5]]
 .c create oval [- $x $r] [- $y $r] [+ $x $r] [+ $y $r]
\end{verbatim}
\endgroup

This is clearly shorter and much easier on the eyes. There is no need to consider the effects of bracing expressions.

Sum of a list becomes
\begingroup\small\begin{verbatim}
 set sum [+ {expand}$list]
\end{verbatim}
\endgroup

\section{Security considerations}

It is worth noting that variadic operators have no way of ``short circuit'' evaluation, much as putative \textbf{\&\&} and \textbf{\tipbar{}\tipbar{}} commands would not. This consideration means that they must be used with caution in cases where expressions have side effects; all their arguments will be evaluated. Commands like
\begingroup\small\begin{verbatim}
   < 1 0 [don't do this!]
   / 0 0 [don't do this!]
\end{verbatim}
\endgroup

will indeed evaluate the string in square brackets.

If expressions like these are constructed from user input, care must be taken to place them in a safe execution environment or otherwise defend against code injection attacks. (This last consideration is somewhat far-fetched, since it is implausible that an injection attack would be able to generate [\tiplangle{} 1 0 [don't do this!]] but not [\tiplangle{} [don't do this!] 0].)

\section{Implementation}

\subsection{Efficiency}

These commands can naturally be compiled and thus as efficient as their corresponding \textbf{expr} operators. The following lines should probably result in the same byte codes.
\begingroup\small\begin{verbatim}
set x [expr {$a * $b + $c}]
set x [+ [* $a $b] $c]
\end{verbatim}
\endgroup

\subsection{Reference Implementation}

Available online at SourceForge [\url{http://sf.net/tracker/?func=detail&aid=1578137&group_id=10894&atid=310894}]. The patch is for this TIP as it stood several versions ago; in particular, it does not implement the ordering comparators and gets associativity wrong in a couple of other cases. Nevertheless, the authors of this TIP believe it to be an adequate proof that the ideas of the TIP are implementable with good performance.

\section{Copyright}

This document has been placed in the public domain.

\section{Colophon}

\textit{TIP AutoGenerator --- written by Donal K. Fellows}
\begin{thebibliography}{TIP \#3}
\addcontentsline{toc}{section}{References}
\bibitem[TIP \#229]{tip229}
Donal K. Fellows,
\emph{Scripted Control of Name Resolution in Namespaces},
on-line at \url{http://purl.org/tcl/tip/229.html}
\bibitem[TIP \#232]{tip232}
Arjen Markus,
Kevin Kenny,
\emph{Creating New Math Functions for the 'expr' Command},
on-line at \url{http://purl.org/tcl/tip/232.html}
\bibitem[TIP \#274]{tip274}
Arjen Markus,
David Smith,
Richard Suchenwirth,
Don Porter,
S\'{e}rgio Loureiro,
\emph{Right-Associativity for the Exponentiation Operator},
on-line at \url{http://purl.org/tcl/tip/274.html}
\end{thebibliography}
\end{document}
