\documentclass[]{article}
\usepackage{amsmath,graphicx,supertabular,hyperref,tabularx,ifthen}
\title{TIP \#212: Temporarily Opening out a Dictionary}
\date{August 11, 2004}
\author{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 \#212}&\textbf{Temporarily Opening out a Dictionary}\\\hline
Author&

Donal K. Fellows \tipmail{donal.k.fellows}{man.ac.uk}
\\
Created&Wednesday, \(\text{11}^{\text{th}}\) August 2004\\
Type&Project\\
Tcl Version&\(8.5\)\\
State&Final\\
Vote&Done\\
Version&\tipversion$Revision: 1.9 $\\
Keywords&tcl, dict, update, script\\
Post History&\\
\hline\end{tabularx}\end{center}
\thispagestyle{empty}\pagestyle{empty}
\begin{tipabstract}

This TIP proposes a new subcommand of \textbf{dict} that associates variables with dictionary entries while a Tcl script (the ``body'' of the command) runs.
\end{tipabstract}
\tableofcontents\setcounter{page}{0}\clearpage\pagestyle{plain}

\section{Rationale}

The standard set of operations provided by the \textbf{dict} command (see \cite{tip111} and \cite{tip163}) give a fairly rich set of operations, but there are always further things that script authors want to do. Instead of ever-expanding numbers of subcommands offering tiny variants on existing operations, this TIP provides a generalized mechanism for associating variables and dictionary entries for the duration of a script. This makes writing arbitrary complex manipulations of dictionaries much simpler.

\section{Proposed Change}

This TIP proposes two new subcommands to \textbf{dict}, \textbf{update} and \textbf{with}, with the following syntaxes and semantics.

\subsection{The 'dict update' Subcommand}

\begin{quote}
\textbf{dict update} \textit{dictVarName dictKey varName} ?\textit{dictKey varName} ...? \textit{bodyScript}
\end{quote}

In prose, the first argument is the name of a variable containing a dictionary that will be updated, the last argument is a script to be executed with the variables set up and whose effects are expected to be to update the associated variables, and the other arguments between those two (of which there must be an even number, with a minimum of two) are a list of dictionary keys and the names of variables with which to associate those keys.

The semantics of the command are this:
\begin{enumerate}
\item{}
For each dictionary key (\textit{dictKey}), the value from the dictionary contained in the variable named by \textit{dictVarName} which that key maps to will be written to the variable associated with that key (\textit{varName}). If the key is not present in the dictionary, the variable will be unset.
\setcounter{enumi}{1}
\item{}
The script (\textit{bodyScript}) is executed.
\setcounter{enumi}{2}
\item{}
The dictionary is read out of \textit{dictVarName} again and, for each \textit{dictKey}, the \textit{varName} variable is consulted and the contained value placed in the dictionary (if \textit{varName} is unset, any existing mapping for \textit{dictKey} will be removed.) Finally, the resulting dictionary value is written back to \textit{dictVarName}.

If the \textit{dictVarName} variable was unset (without being set to a new value) or otherwise rendered unreadable during the execution of \textit{bodyScript}, the updating of the keys and writing back of the resulting dictionary to \textit{dictVarName} is skipped. Note that it is only an unreadable \textit{dictVarName} that is treated this way; it is an error for the variable to contain a value that is not a valid dictionary.
\end{enumerate}

Note that \textit{dictVarName} is read twice (each time, the value read must be a valid dictionary or the variable must be unset, which is interpreted as an empty dictionary) and (assuming the second read succeeds and returns a valid dictionary value) written once, and that \textit{no} traces are set up; \textit{dictVarName} is completely independent of the \textit{varName}s during the execution of \textit{bodyScript}.

Also note that step 3 is carried out even if \textit{bodyScript} completes with a result code other than TCL\_OK, and that the result code of the overall command will be the result code of the script unless TCL\_ERROR was the result of the write-back stage, which might happen if the variable \textit{dictVarName} is updated (during the execution of \textit{bodyScript}) to contain a non-dictionary value, or if the variable \textit{dictVarName} is either unset or cannot be written to (which can happen if a write trace throws an error); note that this mandates that any errors from the \textit{bodyScript} are lost if the write-back phase also throws an error. If the result code is TCL\_OK, the result string/object will be whatever the result string/object of \textit{bodyScript} was.

\subsection{The 'dict with' Subcommand}

\begin{quote}
\textbf{dict with} \textit{dictVarName} ?\textit{key ...}? \textit{bodyScript}
\end{quote}

This is a shorthand version of \textbf{dict update} (named after the Pascal \textit{with} keyword) which maps \textit{all} of the keys in the dictionary in the variable \textit{dictVarName} to variables during the evaluation of \textit{bodyScript}. Note that it builds a list of all the keys in the dictionary before \textit{bodyScript} runs and only those variables which are created are mapped back at the end; if extra keys are defined in the dictionary in the variable during the execution of \textit{bodyScript}, they will be left alone when \textit{bodyScript} finishes.

The variables will be written to and read from in the natural order of the keys of the dictionary in the variable \textit{dictVarName} when the \textbf{dict with} command starts.

When a \textit{key} (or several \textit{key}s) is provided, it describes a path into a nested set of dictionaries (much like with \textbf{dict set}) where the selected leaf indicates a dictionary that is to be opened out. When writing back, non-existence of any key on the path is treated the same as if \textit{dictVarName} itself didn't exist.

\section{Examples}

A somewhat-less-efficient version of \textbf{dict set}:
\begingroup\small\begin{verbatim}
 dict update someVar $key local {
     set local $value
 }
\end{verbatim}
\endgroup

Sorting a list inside a nested dictionary:
\begingroup\small\begin{verbatim}
 dict update someVar OuterKey temp {
     dict update temp InnerKey temp2 {
         set temp2 [lsort $temp2]
     }
 }
\end{verbatim}
\endgroup

``Renaming'' a key:
\begingroup\small\begin{verbatim}
 dict update someVar oldKey foo newKey bar {
     set bar $foo
     unset foo
 }
\end{verbatim}
\endgroup

Opening out a nested dictionary:
\begingroup\small\begin{verbatim}
 dict update someVar OuterKey temp {
     dict with temp {
         # Some script goes in here...
     }
 }
 # Alternative version using a key with 'dict with'...
 dict with someVar OuterKey {
     # Some script goes in here...  
 }
\end{verbatim}
\endgroup

\section{Reference Implementation}

See SF patch 1008768[\url{http://sf.net/tracker/?func=detail&aid=1008768&group_id=10894&atid=310894}].

\section{Copyright}

This document has been placed in the public domain.

\section{Colophon}

\textit{TIP AutoGenerator --- written by Donal K. Fellows}
\begin{thebibliography}{TIP \#2}
\addcontentsline{toc}{section}{References}
\bibitem[TIP \#111]{tip111}
Donal K. Fellows,
David S. Cargo,
\emph{Dictionary Values and Manipulators},
on-line at \url{http://purl.org/tcl/tip/111.html}
\bibitem[TIP \#163]{tip163}
Joe English,
\emph{A [dict merge] Subcommand},
on-line at \url{http://purl.org/tcl/tip/163.html}
\end{thebibliography}
\end{document}
