GeneralAssociative Lists in (La)TeX

LaTeX specific issues not fitting into one of the other forums of this category.
Post Reply
kaare_jensen
Posts: 2
Joined: Mon Aug 15, 2011 12:21 pm

Associative Lists in (La)TeX

Post by kaare_jensen »

Hi,

I need to write a macro that can associate one string with another so I can pass the macro an index string and the macro will then return it's association. The number of associations are in the order of 1000 and are written from a shell script so I can easily include any TeX or LaTeX code and input it in my document.

As an example I would write

Code: Select all

\mymacro{str1}
in the .tex file and I would get "res1" in the document, i.e. the macro have associated str1 with res1.

The input string contains both numbers and underscores so something like

Code: Select all

\newcommand{\str1}{res1}
can not be used.

Any help or guidance is highly appreciated!

Recommended reading 2024:

LaTeXguide.org • LaTeX-Cookbook.net • TikZ.org

NEW: TikZ book now 40% off at Amazon.com for a short time.

Stefan Kottwitz
Site Admin
Posts: 10348
Joined: Mon Mar 10, 2008 9:44 pm

Associative Lists in (La)TeX

Post by Stefan Kottwitz »

Hi,

perhaps the answers here could help: Data structures for TeX.

Stefan
LaTeX.org admin
kaare_jensen
Posts: 2
Joined: Mon Aug 15, 2011 12:21 pm

Associative Lists in (La)TeX

Post by kaare_jensen »

Great, thanks a lot for the pointer and the fast answer!

The expl3 seems to be a LaTeX3 package and I need a solution for LaTeX2e so I guess I can't use that.

The etoolbox, however, has a string compare function that I can use to set an output variable. That way I can also have an error message in case of no match.

The solution I came up with looks like:

Code: Select all

\documentclass{minimal}

\usepackage{etoolbox}

\newcommand{\mymacro}[1]{%
  \def\mout{Error! No match}%
  \ifstrequal{#1}{str1}{\def\mout{res1}}{}%
  \ifstrequal{#1}{str2}{\def\mout{res2}}{}%
  \ifstrequal{#1}{str3}{\def\mout{res3}}{}%
  \mout
}

\begin{document}

Result of str2: \mymacro{str2}.

\end{document}
This solution is not an implementation of an associative list as such, but as long as it solves my problem that is not important.

The question is if this solution ineffective when the number of associations grow above 1000?

So if anybody can see potential problems with my solution or have a better ideas I would still be glad to hear about it.

Thanks!
Post Reply