[Tex/LaTex] Emulate a “tuple” data structure (when you are free to choose the syntax)

data structuresmacrospackage-writing

How can a "tuple" data structure be implemented in LaTeX? The idea is to store several elements (possibly a predefined number) in one macro and then be able to extract each of these elements by index (numeric or otherwise).

\documentclass{article}

% HOW TO IMPLEMENT THIS?
\newcommand{\definetuple}[...]{...}
\newcommand{\extractfromtuple}[...]{...}
% HOW TO IMPLEMENT THIS?

% YOU ARE FREE TO CHANGE SYNTAX HERE
\definetuple{first}{Alice}{Munich}{Germany}
\definetuple{second}{Bob}{London}{United Kingdom}

\begin{document}
  \extractfromtuple{first}{1} lives in \extractfromtuple{first}{2}
  which is located in \extractfromtuple{first}{3};
  this may or may not be true for \extractfromtuple{second}{1}.
\end{document}
% YOU ARE FREE TO CHANGE SYNTAX HERE

I'd like to split the original question so that nice solutions with a new API have a place to live. Should this be community wiki?

Best Answer

\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\NewDocumentCommand{\definetuple}{mmmm}
  {
   \tl_new:c { g_tuple_#1_tl }
   \tl_gset:cn { g_tuple_#1_tl } { {#2} {#3} {#4} }
  }
\DeclareExpandableDocumentCommand{\extractfromtuple}{mm}
  {
   \tl_item:cn { g_tuple_#1_tl } { #2-1 }
  }
\ExplSyntaxOff
\begin{document}
\definetuple{alice}{Alice}{Munich}{Germany}
\definetuple{bob}{Bob}{London}{United Kingdom}

\extractfromtuple{alice}{3}

\extractfromtuple{bob}{1}

\end{document}

In this simple case I've used a token list; for more complex tasks a sequence would be better, perhaps.

Another approach might be with property lists.

\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\NewDocumentCommand{\definetuple}{mmmm}
  {
   \prop_new:c { g_tuple_#1_prop }
   \prop_gput:cnn { g_tuple_#1_prop } { name }    {#2}
   \prop_gput:cnn { g_tuple_#1_prop } { town }    {#3}
   \prop_gput:cnn { g_tuple_#1_prop } { country } {#4}
  }
\DeclareExpandableDocumentCommand{\extractfromtuple}{mm}
  {
   \prop_get:cn { g_tuple_#1_prop } { #2 }
  }
\ExplSyntaxOff
\begin{document}
\definetuple{alice}{Alice}{Munich}{Germany}
\definetuple{bob}{Bob}{London}{United Kingdom}

\extractfromtuple{alice}{country}

\extractfromtuple{bob}{name}

\end{document}

Here the available keys are name, town and country. I'd prefer this approach for more complicated tasks, where, for example, data are added one piece of information at a time; for example one could define

\NewDocumentCommand{\addtotuple}{mmm}
  {
   \prop_gput:cnn { g_tuple_#1_prop } { #2 } { #3 }
  }

and \addtotuple{alice}{town}{Berlin} would move Alice to the north.

Related Question