I've been trying to implement a macro that reads and transforms its argument into a different form...but I'm having quite a bit of trouble finding or creating even the most basic parsing tools.
Case in point: I can't find a way to make a safe version of either car (which returns the first element of a list) or cdr (which returns the rest of the list).
I learned from this answer that LaTeX includes implementations named \@car and \@cdr, defined as follows:
\def\@car#1#2\@nil{#1}
\def\@cdr#1#2\@nil{#2}
However, both of these can only be used alone, no nesting is possible.
For example, the following produces an error:
\@car \@cdr content\@nil\@nil
The correct output, if \car and \cdr worked as in Lisp, would be 'o': the first element of the rest of the argument passed to \cdr.
However, \@car runs first, and doesn't execute its input, taking \@cdr as #1 and content as #2, and returns \@cdr.
This leaves the remaining input as \@cdr\@nil, which results in the error "Paragraph ended before \@cdr was complete".
We also can't use \@cdr more than once to trim off more than the first token, if we try:
\@cdr \@cdr content\@nil\@nil
...the result is content\@nil, because the first \@cdr discards the second before it is run.
I feel like the answer would be something along the lines of
\def\car#1{\@car #1\@nil}
\def\cdr#1{\@cdr #1\@nil}
...if it were possible to tell TeX to evaluate #1 until it contains no macros before passing it to \@car or \@cdr.
To that end, I've also tried:
\def\car#1{\edef\temp{#1}\expandafter\@car\temp\@nil}
\def\cdr#1{\edef\temp{#1}\expandafter\@cdr\temp\@nil}
...which again works correctly for \car{content} or \cdr{content}, but causes compilation of the document to silently fail for \car{\cdr{\cdr{content}}}, and I have no idea why.
Any ideas on how car and cdr could be implemented safely?
\@carand\@cdrcome from LaTeX. – Theodore Murdock Jul 26 '12 at 06:01