\documentclass[]{article}
\usepackage{amsmath,graphicx,supertabular,hyperref,tabularx,ifthen}
\title{TIP \#170: Better Support for Nested Lists}
\date{January 30, 2004}
\author{Sergey Babkin, Don Porter, 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 \#170}&\textbf{Better Support for Nested Lists}\\\hline
Author&

Sergey Babkin \tipmail{babkin}{freebsd.org}
\par
Don Porter \tipmail{dgp}{users.sf.net}
\par
Donal K. Fellows \tipmail{dkf}{users.sf.net}
\\
Created&Friday, \(\text{30}^{\text{th}}\) January 2004\\
Type&Project\\
Tcl Version&\(8.7\)\\
State&Draft\\
Vote&Pending\\
Version&\tipversion$Revision: 1.6 $\\
Post History&\\
\hline\end{tabularx}\end{center}
\thispagestyle{empty}\pagestyle{empty}
\begin{tipabstract}

Nested lists are easy to create with Tcl but then manipulating them is not easy. For example, think about how to change a value nested in a list 2 levels deep? How about 4 levels deep? The proposed new commands make such manipulation easy, and make the nested lists a great replacement for arrays and structures in C-like languages.
\end{tipabstract}
\tableofcontents\setcounter{page}{0}\clearpage\pagestyle{plain}

\section{Rationale and Specification}

The new proposed commands start with the prefix ``ldeep''. They are desgined to resemble the classic list commands with ``l'' names. In the cases when the meaning of ``ldeep'' command differs substantially from the ``l'' command, the name has been selected to be different (such as ``ldeeprep'', not ``ldeepreplace'').

The commands have been extensively used in the Not A Commander project [\url{http://nac.sf.net/}] and have been adjusted to the observed needs of practical use. All these commands use the concept of ``path'' (see \cite{tip22}) and handle the concatenation of paths for reasons of convenience (e.g. a ``base'' path followed by a ``local'' path).

\subsection{Commands}

The new proposed commands are:

\begin{quote}
\textbf{ldeepset} \textit{listvar path} ?\textit{path}?... \textit{value}
\end{quote}

Set a \textit{value} in a nested list variable. If the variable did not exist previously, it is created. If the intermediate lists specified in the path did not exist, they are created as empty lists. This includes the ``filler'' elements: for example, if \textit{listvar} contained a list of one element and the path starts with ``5 ...'', the elements with indexes 1, 2, 3, 4 and 5 will all be created (and will contain empty strings) and the the further creation within the element at index 5 will proceed.

A special meaning is assigned by this command to the negative indexes in the path: they mean ``add a new element at the end of the list''. So this command also doubles as a nested version of lappend. For example,
\begingroup\small\begin{verbatim}
   ldeepset listvar -1 value
\end{verbatim}
\endgroup

means the same thing as
\begingroup\small\begin{verbatim}
   lappend listvar value
\end{verbatim}
\endgroup

This merging has happened because it's often neccessary to add elements to the lists in the middle of the path. The particular value used to indicate the addition of an element can be changed to something more symbolic, for example to ``append'' instead of a negative value.

The \textit{ldeepset} command returns nothing. Since the version without value as in the common set can not be used, returning the value did not seem to make sense. Also when experimenting with large lists from the command line, returning the value that is a large list itself would cause a long and unpleasant printout of it.

\textit{(This is only partially superceded by \cite{tip33} and \cite{tip331}.)}

\begin{quote}
\textbf{ldeepincr} \textit{lstvar path} ?\textit{path}?... \textit{int-value}
\end{quote}

Increase a value within a nested list by \textit{int-value}. Note that since the amount of increase has to be differentiated from the \textit{path}, it's mandatory even for the value of 1. This is a convenient and often used shortcut for the \textbf{ldeepindex}-\textbf{expr}-\textbf{ldeepset} sequence. It returns the value of the element after increase.

\begin{quote}
\textbf{ldeeprep} \textit{lstvar path} ?\textit{path}?... \textit{first last element-list}
\end{quote}

Replace a range of elements in a sublist identified by the \textit{path} with the elements from the \textit{element-list}. It returns nothing.

This command is different from \textbf{lreplace} in two ways, hence the name change. First, it acts on data in a variable, not on a list as an argument. Second, the elements for replacement are contained in a list, not as separate elements on command line. Both differences were created for convenience of practical use, plus to allow the path to pick up the variable number of arguments. I have found that I always need to replace elements in a variable, not as a pass-through operator, and that I almost always need to insert elements from another list, not just some fixed set of elements.

\begin{quote}
\textbf{ldeeppop} \textit{lstvar path} ?\textit{path}?... \textit{count}
\end{quote}

Remove \textit{count} elements from the end of the sublist identified by \textit{path} in the variable and return them in a list.

This command was inspired by the pop operator in Perl. Somehow I've never has a very string need for the other similar commands (which would be \textit{ldeeppush} to add elements, and \textit{ldeepshift} and \textit{ldeepunshift} for operations on the start of the list) but they can be easily added as well for completeness.

The command returns the list of the popped elements in the original order. For example, if \textit{lstvar} contained \{0 1 2 3 4 5\}, ``ldeeppop lstvar \{\} 2'' would return \{4 5\}, NOT \{5 4\}.

\section{Other Extensions for List Support}

In my practice I have found that a few other commands make working with lists much more convenient. They are not directly related to the nested lists but to the lists in general.

\begin{quote}
\textbf{lconcat} \textit{sublist} ?\textit{sublist}?...
\end{quote}

Concatenate the argument lists and return the resulting list. This command is similar to \textbf{concat} but avoids converting the values to strings, concatenating the strings and then re-parsing the strings. When the lists involved grow to a few megabytes, \textbf{concat} can become very inefficient both in the sense of time and memory usage; \textbf{lconcat} resolved this inefficiency. Note that it does \textit{not} replace \textbf{concat}, which can be used to assemble lists from pieces in different argument strings. The command returns the concatenated list.

\textit{(Note that this is largely possible through using} \textbf{list} \textit{and \cite{tip157}/\cite{tip293}, and that} \textbf{concat} \textit{is more likely to handle the lists where this matters efficiently anyway right now due to efficiency tweaks to its implementation. It remains to be seen whether there is still a need for} \textbf{lconcat} \textit{in other areas...)}

\section{Reference Implementation}

The reference implementation is available as part of the Not A Commander project [\url{http://nac.sf.net/}], the source file \textit{cutil.c}. To include the new commands into Tcl, the error messages will have to be adjusted to match the style used in Tcl, and the man pages will have to be written. The current implementation has been tested in fair amounts for both correctness and efficiency by usage in the Not A Commander project, the formal test suite would have to be written. Further progress in this direction depends on acceptance of this proposal.

\section{Comments}

Messages on the TCLCORE mailing list have pointed out that nearly everything proposed here is either equivalent to, or trivially created by composition of the existing commands \textbf{lindex}, \textbf{lrange}, \textbf{lset}, \textbf{lassign}, and \textbf{lrepeat}. The only novel thing proposed is the ability of \textbf{lset} to create new list elements. If that's still desired, a separate new TIP proposing that alone would be the best way to deal with that.

I call on the author to withdraw this TIP.

\section{Copyright}

This document has been placed in the public domain.

\vspace{3ex}\hrule\vspace{1.5ex}

\section{Appendix: Removed Commands}

\textit{These commands were originally part of this TIP, but have been removed to this appendix on the grounds that the functionality they describe is now part of Tcl via other TIPs.}

\begin{quote}
\textbf{ldeepindex} \textit{list path} ?\textit{path}?...
\end{quote}

Extract an element from a nested list. The element is identified by the logical concatenation of the paths. It returns the extracted element. \textit{(Obsoleted by \cite{tip22}.)}

\begin{quote}
\textbf{ldeeplen} \textit{list path} ?\textit{path}?...
\end{quote}

Find the length of a nested sublist. The sublist is identified by the logical concatenation of the paths. It returns the found length. A non-existing sublist is assumed to have the length of 0. \textit{(Obsoleted by \cite{tip22} and normal llength.)}

\begin{quote}
\textbf{ldeeprange} \textit{list path} ?\textit{path}?... \textit{first last}
\end{quote}

Extract a sublist from a nested list. This command is a convenient equivalent of
\begingroup\small\begin{verbatim}
   lrange [ldeepindex list path ?path?] first last]
\end{verbatim}
\endgroup

``end'' is supported as the first or last index. It returns the extracted sublist. \textit{(Obsoleted by \cite{tip22} and normal lrange.)}

\begin{quote}
\textbf{mset} \textit{list-of-variable-names list-of-values}
\end{quote}

Set the values from the value list to the variable in the variable list at the same index. The command name stands for ``multiple set''. This command is inspired by assignments in Perl.

If there were more variables than the values, the rest of variables are set to an empty value. If there were more values than variables, then the last variable is assigned the whole end of a list (as a list).

A special variable name ``\textbf{-}'' can be used to throw away a value, or the whole end of the value list if it's specified as the last one in the variable list.

The command returns nothing. It can be argued that it would make sense to return the length of the original list, or the difference between the length of the values list and the length of the variables list. I don't know which one is better.

This command is particularly convenient for returning multiple values from a procedure. For example:
\begingroup\small\begin{verbatim}
   proc xxx {a b} {
      return [list [expr $b+$a] [expr $b*$a]]
   }
   mset {sum product} [xxx 1 2]
\end{verbatim}
\endgroup

\textit{(Obsoleted by \cite{tip57}.)}

\begin{quote}
\textbf{ldup} \textit{count element} ?\textit{element}?...
\end{quote}

This returns a list produced by duplicating the sequence of elements \textit{count} times. This command is inspired by the operator ``x'' in Perl, and it is a logical equivalent of:
\begingroup\small\begin{verbatim}
   proc ldup {count args} {
      set res {}
      for {set i 0} {$i < $count} {incr i} {
         set res [lconcat $res $args]
      }
      return $res
   }
\end{verbatim}
\endgroup

\textit{(Obsoleted by \cite{tip136}.)}

\begin{quote}
\textbf{lvdup} \textit{count element-list}
\end{quote}

This returns a list produced by duplicating the \textit{element-list count} times. This command is inspired by the operator ``x'' in Perl, and it is a logical equivalent of:
\begingroup\small\begin{verbatim}
   proc lvdup {count list} {
      set res {}
      for {set i 0} {$i < $count} {incr i} {
         set res [lconcat $res $list]
      }
      return $res
   }
\end{verbatim}
\endgroup

\textit{(Obsoleted by \cite{tip136} and \cite{tip157}/\cite{tip293}.)}

\section{Colophon}

\textit{TIP AutoGenerator --- written by Donal K. Fellows}
\begin{thebibliography}{TIP \#7}
\addcontentsline{toc}{section}{References}
\bibitem[TIP \#22]{tip22}
David Cuthbert,
Kevin Kenny,
Don Porter,
Donal K. Fellows,
\emph{Multiple Index Arguments to lindex},
on-line at \url{http://purl.org/tcl/tip/22.html}
\bibitem[TIP \#33]{tip33}
Kevin Kenny,
\emph{Add 'lset' Command to Assign to List Elements.},
on-line at \url{http://purl.org/tcl/tip/33.html}
\bibitem[TIP \#57]{tip57}
Donal K. Fellows,
Agnar Renolen,
Don Porter,
\emph{Move TclX's [lassign] into the Tcl Core},
on-line at \url{http://purl.org/tcl/tip/57.html}
\bibitem[TIP \#136]{tip136}
Simon Geard,
\emph{Large List Initialisation},
on-line at \url{http://purl.org/tcl/tip/136.html}
\bibitem[TIP \#157]{tip157}
Kevin B. Kenny,
Peter Spjuth,
Donal K. Fellows,
Don Porter,
\emph{Argument Expansion with Leading \{expand\}},
on-line at \url{http://purl.org/tcl/tip/157.html}
\bibitem[TIP \#293]{tip293}
Miguel Sofer,
\emph{Argument Expansion with Leading \{*\}},
on-line at \url{http://purl.org/tcl/tip/293.html}
\bibitem[TIP \#331]{tip331}
Kevin B. Kenny,
\emph{Allow [lset] to Extend Lists},
on-line at \url{http://purl.org/tcl/tip/331.html}
\end{thebibliography}
\end{document}
