\documentclass[]{article}
\usepackage{amsmath,graphicx,supertabular,hyperref,tabularx,ifthen}
\title{TIP \#70: A Relational Switch Control Structure}
\date{October 20, 2001}
\author{Bhushit Joshipura, Donal K. Fellows}
\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 \#70}&\textbf{A Relational Switch Control Structure}\\\hline
Author&

Bhushit Joshipura \tipmail{bhushit}{hotmail.com}
\par
Donal K. Fellows \tipmail{fellowsd}{cs.man.ac.uk}
\\
Created&Saturday, \(\text{20}^{\text{th}}\) October 2001\\
Type&Project\\
Tcl Version&\(8.5\)\\
State&Withdrawn\\
Vote&Pending\\
Version&\tipversion$Revision: 1.8 $\\
Post History&\\
\hline\end{tabularx}\end{center}
\thispagestyle{empty}\pagestyle{empty}
\begin{tipabstract}

This TIP proposes the introduction of a new control structure, \textit{rswitch}, which is a relational parallel to switch-case control structure. It consists of two lists: condition list and situation-reaction list. At the maximum two conditions can be specified. Based on situation, reaction is executed. The situation is selected on ``first true and only the first true'' basis.
\end{tipabstract}
\tableofcontents\setcounter{page}{0}\clearpage\pagestyle{plain}

\section{Rationale}

Theoretically only two controls --- \textit{if} and \textit{goto} --- are sufficient to implement all algorithms. However, languages provide more control structures for better representation of algorithms. To many structural programmers like me, a \textit{switch} statement gives much better picture of the program than equivalent \textit{if}-\textit{elseif}-...-\textit{else} chain. It pronounces the course of decision of a big chunk of program in a single statement, making understanding and maintaining software easier. It also helps to optimize the software better if it is written in \textit{switch} form. However, \textit{switch} is strictly data based i.e. \textit{switch} happens strictly on data value. 

The proposed \textit{rswitch} command is a control structure similar to (and more general than) \textit{switch}. (As a matter of fact, Tcl's \textit{foreach} control structure is a special case of its for control structure.) Using \textit{rswitch} it should be possible to take decisions based on relations between entities.

In response to comments on Revision: 1.2 of the draft, Bhushit Joshipura wrote [Re-edited]:

Why rswitch? [Re-written] 
\begin{enumerate}
\item{}
if..elseif..else contains elements of surprize spread in the code. From maintenance point of view, once the \textit{if}..\textit{elseif}..\textit{else} code goes beyond horizon (one display length), burden of reference retention comes on human brain making maintenance bug-prone.
\setcounter{enumi}{1}
\item{}
In case of \textit{rswitch}, if a situation refers to one or more conditions, we had reduced this burden by stating upfront which variable is in the spotlight. The maintainer can then easily jump irrelavant cases. 
\setcounter{enumi}{2}
\item{}
In \textit{if}..\textit{elseif}..\textit{else}, a string of three conditions (with one of them being a `not' string) can mystify me for at least an hour. 
\setcounter{enumi}{3}
\item{}
In case of an \textit{rswitch} (even in a situation which does not refer to any conditions):
\begin{enumerate}
\item{}
`and' is nested rswitch
\setcounter{enumii}{1}
\item{}
`or' is a fall through case
\setcounter{enumii}{2}
\item{}
`not' could be written as ``default'' case. `not' free from `and' and `or' is less confusing. We can write almost a `not-less' code using ``default''. 
\end{enumerate}

Logical connectives result into visual presentation.
\setcounter{enumi}{4}
\item{}
Object Oriented Programming is trying to eliminate \textit{switch-case} statements by identifying localization of references and finding a heirarchy of data-actions. 
\setcounter{enumi}{5}
\item{}
In similar way one can think of \textit{rswitch} cases (situations). Identifying localized references (w.r.t. situations) and a heirarchy of situations-reactions. However, this is a research issue.
\end{enumerate}

Moreover, the writer does not need to be an artist to be able to write understandable code.

\section{Implementation in Other Languages}

I queried about proposal of such a control structure in C to Dr. Dennis M. Ritchie in February 2001. (At that time I thought only of bi-conditional relational switch. See a few pages down for currently proposed control structure.)

\begin{quote}
Absence of relational switch I know this can be odd for other languages --- but not for C. C is so near to machine and a relational switch could be ideal for many many machine-cycle saving situations.
\end{quote}
\begin{description}
\item[Apart from machine-orientedness, it could avoid many usages of not-so-structured ?]
 operator.

It could simplify a lot of control and signal processing code too.

Why did C become more data-biased for a control structure?
\begingroup\small\begin{verbatim}
    relational-switch(expr1,expr2){
    case ==: statements;
            break;
    case > : statements;
            break;
    case < : statements;
            break;
    default: statements;
            break;
    }
\end{verbatim}
\endgroup
\end{description}

TCL need not be so optimized, as C has to be. However, clarity and maintainability remain formidable reasons for relational switch implementation.

In a quick reply, Dr. Ritchie wrote back:

\begin{quote}
The relational switch idea is (so far as I know) for C a new suggestion, although I have no idea of all things that were proposed for the 1989 or 1999 C standards. If seems to hark back to the old Fortran GOTO statement
\end{quote}
\begingroup\small\begin{verbatim}
    IF (expression) 2, 3, 4
\end{verbatim}
\endgroup

\begin{quote}
which went to various places depending on whether the expression was -, 0 or +. It's also a bit strange syntactically (though it might work in the grammar) in that the case values aren't expressions, but just operators.
\end{quote}

\begin{quote}
Regards, Dennis"
\end{quote}

Thus the structure is absent from C and its whole family. It is absent from Pascal, PERL, BASIC, shell scripts --- and of course, TCL.

Fortran's computed goto is near to bi-conditional rswitch. (That way Chimpanzees are near to Homo sapiens too.) However, clarity of presentation of default and fall through are not achievable through computed goto. Mono-conditional rswitch, however, does not have a parallel in languages of my knowledge (C, C++, Java, Pascal, BASIC, Fortran, shell scripts). 

\section{Grammar and Behavior}

Overall:
\begingroup\small\begin{verbatim}
rswitch {[condition(s)]} {
    <situation-1> {
        <reaction-block-1>
    }
    ...
}
\end{verbatim}
\endgroup

The condition list may have no, one or two variables.

A situation is legal if:
\begin{enumerate}
\item{}
It is a valid expression or
\setcounter{enumi}{1}
\item{}
If the condition list had at least one element 'x', \{\$x \$situation\} is a valid expression or
\begin{enumerate}
\item{}
If the condition list had exactly one element 'x', \{\$situation \$x\} is a valid expression or
\setcounter{enumii}{1}
\item{}
If the condition list had two elements 'x' and 'y', \{\$x \$situation \$y\} is a valid expression or
\end{enumerate}
\setcounter{enumi}{2}
\item{}
If the condition list had two elements 'x' and 'y' and \{\$situation \$y\} is a valid expression or
\setcounter{enumi}{3}
\item{}
If \$situation == ``default''
\end{enumerate}

A reaction block is legal if:
\begin{enumerate}
\item{}
It is not the last block and \$reactionBlock == ``-'' (fall through) or
\setcounter{enumi}{1}
\item{}
It is a valid TCL action block
\end{enumerate}

Let us call a non-default extracted valid expression a SITUATION.

At execution, reaction block following or fell through by the first and only the first SITUATION that becomes true, is executed. In case no SITUATION becomes true and default situation is present, reaction block following or fell through by default statement is executed. Default situation is not necessary for operation of rswitch. An rswitch without any situation-reaction block is grammatically valid.

\section{Sample Invocations}
\begingroup\small\begin{verbatim}
# Full length condition block. Second condition perhaps got redundant with maintenance.
rswitch {$a $b} {
   {> $c} -
   {< $d} {
      puts "$a is either > $c or < $d or both"
   }
   {< $c} {
      # Full length condition block. Second condition is used.
      rswitch {$a $d} {
         > {
            puts "$a is < $c AND > $d"
         }
         == {
            puts "$a and $d are equal and they are < $c"
         }
         default {
            puts "$a is < $c BUT <= $d"
            puts "should never come here"
         }
      }
   }
   {3 > } {
      puts "$a == $c, $a >= $d and $b <= 3"
   }
   default {
      puts "$a == $c, $a >= $d and $b >= 3"
   }
}
\end{verbatim}
\endgroup

\section{Contrast}

Contrast above code with its if-elseif-else equivalent. Notice that:
\begin{enumerate}
\item{}
Both the examples have same effect.
\setcounter{enumi}{1}
\item{}
Both examples are indented with the same style.
\begingroup\small\begin{verbatim}
if {($a > $c) || ($a < $d)} {
	# could you see a maintenance nightmare that could have arisen when
	# reference to $b were eliminated?
	puts "$a is either > $c or < $d or both"
} elseif {$a < $c} {
	if {$a > $d} {
		puts "$a is < $c AND > $d"
	} elseif {$a == $d} {
		puts "$a and $d are equal and they are < $c"
	} else {
		puts "Pop-up question: What should we have here?
		puts "$a is < $c BUT <= $d"
		puts "should never come here"
	}
} elseif {3 > $b} {
		puts "$a == $c, $a >= $d and $b <= 3"
} else {
		puts "$a == $c, $a >= $d and $b >= 3"
}
\end{verbatim}
\endgroup
\end{enumerate}

\section{Responses to Revision 1.2}

Revision 1.3 tries to reflect suggestions from various of the following contributors. Thanks.

John Ousterhaut wrote:

\begin{quote}
This is certainly a novel suggestion, but I'm not sure how useful it is. The proposed new command doesn't seem much clearer or much more efficient than an ``if... elseif ... elseif...'' statement. One of the arguments for a ``switch'' statement over ``if ... elseif ...'' is that there can be many branches in a ``switch'' statement. However, it seems unlikely to me that there would be more than a couple of branches in the proposed new ``rswitch'' statement, so its value seems marginal to me. In the absence of compelling value, I'd suggest leaving it out to avoid language bloat.
\end{quote}

Kevin B. Kenny wrote:

\begin{quote}
I don't want to discourage language experimentation, but I question whether the Tcl core is the right place to do it. The 'rswitch' that is being requested can be done just as well with an extension --- except for bytecode compilation, which can come later -{}- and exposed to programmers that way. If it becomes sufficiently popular, it can then be integrated into the core.
\end{quote}

Don Porter wrote: 

\begin{quote}
Agreed. A natural place to offer this command would be in the control package of tcllib. Let's put it there, and if it proves to be indispensible, we can consider moving it into Tcl itself at that time.
\end{quote}

Mohan L. Gundu wrote: 

\begin{quote}
What I had in mind is to extend the 'rswitch' case block so that it can accept multiple conditional relationships in a single statement.
\end{quote}

\begin{quote}
I can also think of another usage of 'rswitch' which doesn't take any arguments at all. A vanilla version which is just replacement to if-elseif-elseif-..-else structure but only that code is more easier to read...
\end{quote}
\begingroup\small\begin{verbatim}
rswitch { 
	($a > 4): /* block 1 */ 
	($b < 100): /* block 2 */
	($c > 5 ): /* block 3 */ 
	($d == 10): /*block 4 */ 
}
\end{verbatim}
\endgroup

Don Porter wrote:

\begin{quote}
Rather than defining two forms of the command, mono-conditional and bi-conditional, why not use the power of Tcl to allow for both and even more possibilities within a singleform? 
\end{quote}

\begin{quote}
Consider:
\end{quote}
\begingroup\small\begin{verbatim}
rswitch $formatString { 
	$sub1 $body1
	...
	$subN $bodyN 
} 
\end{verbatim}
\endgroup

\begin{quote}
Then have [rswitch] construct the Tcl expressions to be tested using [format]: 
\end{quote}
\begingroup\small\begin{verbatim}
format $formatString $sub1 
\end{verbatim}
\endgroup
\begin{description}
\item[So you could have]

\begingroup\small\begin{verbatim}
rswitch {$a %s $b} { 
	> {puts "$a is greater than $b"} 
	< {puts "$a is less than $b"} 
	== {puts "$a equals $b"} 
} 
\end{verbatim}
\endgroup

or
\begingroup\small\begin{verbatim}
rswitch {$a %s} {
	1 {puts "$a > 1"}
	5 {puts "$a > 5"}
	15 {puts "$a > 15"}
	{>$b} {puts "$a > $b"}
	{<$b} - > {==$b} {puts "$a <= $b"} 
} 
\end{verbatim}
\endgroup

Extending this idea further, consider the possibility of using [format] to create the expression like so:
\begingroup\small\begin{verbatim}
eval [linsert $sub1 0 format $formatString] 
\end{verbatim}
\endgroup

Then the substitutions could be lists of multiple values to substitute into multiple \%-conversion specifiers in the format string, allowing for the construction of quite elaborate expressions.
\end{description}

Brent Welch wrote

\begin{quote}
I like Don's suggestion. I'm reminded of the switch statement in the tclhttpd state machine, crafted by Steve Uhler:
\end{quote}
\begingroup\small\begin{verbatim}
set state [string compare $readCount 0],$data(state) 
switch -glob -- $state {
	1,start { # Read something in the start state } 
	0,start { # Read empty line in the start state 
	1,mime  { # Read something in the mime state }
	0,mime  { # Read blank line in the mime state }
	-1,*    { # Read error in any state }
	default { # Unexpected condition }
}
\end{verbatim}
\endgroup

\begin{quote}
I had had a bunch of nested if-then-else's, of course. With an artful creation of the switch value and the power of things like glob, you can really create compact, expressive switch statements already.
\end{quote}

\section{Sample Implementation}

Will be provided later.

\section{Copyright}

This document is placed in public domain.

\section{Colophon}

\textit{TIP AutoGenerator --- written by Donal K. Fellows}
\end{document}
