\documentclass[]{article}
\usepackage{amsmath,graphicx,supertabular,hyperref,tabularx,ifthen}
\title{TIP \#342: Dict Get With Default}
\date{November 27, 2008}
\author{Lars Hellström}
\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 \#342}&\textbf{Dict Get With Default}\\\hline
Author&

Lars Hellström \tipmail{Lars.Hellstrom}{residenset.net}
\\
Created&Thursday, \(\text{27}^{\text{th}}\) November 2008\\
Type&Project\\
Tcl Version&\(8.7\)\\
State&Draft\\
Vote&Pending\\
Version&\tipversion$Revision: 1.3 $\\
Keywords&dictionary, default value\\
Post History&\\
\hline\end{tabularx}\end{center}
\thispagestyle{empty}\pagestyle{empty}
\begin{tipabstract}

A new subcommand of \textbf{dict} is proposed, which returns a dictionary value if it exists and returns a per-call default otherwise.
\end{tipabstract}
\tableofcontents\setcounter{page}{0}\clearpage\pagestyle{plain}

\section{Specification}

The \textbf{dict} command will get a new subcommand

\begin{quote}
\textbf{dict getwithdefault} \textit{dictionary} \textit{key} ?\textit{key} ...? \textit{value}
\end{quote}

(I consider the name of this subcommand very much open for discussion) which modulo error messages behaves like
\begingroup\small\begin{verbatim}
 proc dict_getwithdefault {D args} {
     if {[dict exists $D {*}[lrange $args 0 end-1]]} then {
         dict get $D {*}[lrange $args 0 end-1]
     } else {
         lindex $args end
     }
 }
\end{verbatim}
\endgroup

i.e., it returns the value from the \textit{dictionary} corresponding to the sequence of \textit{key}s if it exists, or the default \textit{value} otherwise. As with \textbf{dict exists}, it is OK (and will cause the default \textit{value} to be returned) if one of the \textit{key}s is missing from its dictionary, but an error is thrown if this path of keys cannot be traversed because the value associated with the previous key is not a dictionary.

\section{Rationale}

It is clear that getting a value from a dictionary if it exists and using a default otherwise is a common operation, but it is also clear that this can be carried out with a combination of existing Tcl commands. Hence the issue is whether a new subcommand for this improves efficiency and convenience of this operation enough to justify the possible bloat it brings.

\subsection{Alternative Methods}

One approach that has been suggested for providing default values is to combine \textbf{dict get} with \textbf{dict merge}, like so:
\begingroup\small\begin{verbatim}
  dict get [dict merge {-apa bar} $D] -apa
\end{verbatim}
\endgroup

This approach is however appropriate mainly in situations where several keys are given fixed defaults simultaneously. Compared to \textbf{dict getwithdefault}, it has the following disadvantages:
\begin{itemize}
\item{}
It cannot be used for keys in nested dictionaries.
\item{}
It takes time proportional to the size of the dictionary, even when only one value is inspected. Since \textbf{dict filter key} has an optimisation for this kind of situation, there are apparently maintainers which consider such differences relevant.
\item{}
The ``one \textbf{dict merge} early providing defaults for all keys'' approach cannot deal with keys that have dynamic defaults, e.g. that the default for option -foo is the effective value of option -bar.
\end{itemize}

Hence although \textbf{dict merge} is sometimes appropriate for providing defaults, it is not a universal solution.

The basic approach is instead to, as in the \textbf{dict\_getwithdefault} proc above, first use \textbf{dict exists} and then \textbf{dict get} if the value existed. Problems with this approach are:
\begin{description}
\item[* It is redundant]
already \textbf{dict exists} retrieves the value, but doesn't return it, so \textbf{dict get} has to look it up all over again.
\item[* It is bulky]
if the value in dictionary \textit{D} of option \textbf{-apa} (or its default \textbf{bar}) is to be passed as an argument to the command \textbf{foo}, then the complete command is
\begingroup\small\begin{verbatim}
     foo [if {[dict exists $D -apa]} then {dict get $D -apa}\
       else {return -level 0 bar}]
\end{verbatim}
\endgroup

or 
\begingroup\small\begin{verbatim}
     foo [expr {[dict exists $D -apa] ? [dict get $D -apa] : "bar"}]
\end{verbatim}
\endgroup

which many programmers would find objectionable. The \textbf{dict getwithdefault} counterpart is merely
\begingroup\small\begin{verbatim}
     foo [dict getwithdefault $D -apa bar]
\end{verbatim}
\endgroup
\end{description}

The only way to avoid the redundance of an extra look-up seems to be to combine \textbf{dict get} with \textbf{catch}, like so:
\begingroup\small\begin{verbatim}
  if {[catch {dict get $D -apa} value]} then {set value bar} else {set value}
\end{verbatim}
\endgroup

but this has the disadvantage of hiding other sources of error, such as \textit{D} not being a dictionary in the first place. This kind of error in a normal processing path is also considered poor style by some.

\subsection{Implementation Choices}

Even if it is deemed appropriate to have a dedicated subcommand of \textbf{dict} for this, it could be argued that it needn't be part of the compiled Tcl core; since \textbf{dict} is an ensemble, anyone can extend it at the script level and ``the core can do without this bloat''. However, it turns out than an in-core implementation is very easy whereas the alternatives are not so easy.

Concretely, the necessary DictGetWithDefaultCmd is a trivial modification of DictExistsCmd, to take one extra argument after the \textit{key}s and change the final
\begingroup\small\begin{verbatim}
  Tcl_SetObjResult(interp, Tcl_NewBooleanObj(valuePtr != NULL));
\end{verbatim}
\endgroup

to
\begingroup\small\begin{verbatim}
  Tcl_SetObjResult(interp, valuePtr != NULL ? valuePtr : objv[objc-1]);
\end{verbatim}
\endgroup

It is nowhere near as easy to do this in a well-behaved extension, since DictExistsCmd relies on TclTraceDictPath to do most of the work, and the latter is AFAICT at best available in the internal stubs table.

A script-level implementation is certainly possible, but the minute details of producing core-looking error messages in this case appears considerable both compared to the functional parts of the command and compared to the amount of code needed to do it in the core.

\section{Reference Implementation}

An implementation is provided on SF, in patch \#2370575. [\url{https://sourceforge.net/support/tracker.php?aid=2370575}]

\section{Copyright}

This document has been placed in the public domain. 

\section{Colophon}

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