[Tex/LaTex] Using prefix notation

formattingmath-modespacing

I want to show prefix notation in my document, somewhat like this:

+ (x 5 3) (- 6 4)

However, I want to enter it in maths mode, but maths mode removes all the spaces, so I get

+(x53)(-64)

Which has rather a different meaning. Obviously I could add spaces explicitly, but

$+\;(\times\;5\;3)\;(-\;6\;4) $

is not exactly readable in the source.

Any better ways of doing this?

Best Answer

What you want to write is something very similar to s-expressions. I was thinking some package might already be there to help you write these, but couldn't find anything after some googling. Anyway, the following TeX macro seems to do the work

\documentclass{article}
\makeatletter
\def\sx@stop{\relax}\def\sx@open{(}\def\sx@close{)}
\def\sx@scan#1{%
  \def\sx@arg{#1}%        save the current token
  \ifx\sx@arg\sx@stop   % is it the end of the list?
    \let\sx@next\relax
  \else
    \ifx\sx@arg\sx@close\else\sx@space\fi % add space unless token is ")"
    {\sx@arg}%                            % write the token
    \ifx\sx@arg\sx@open                   
      \let\sx@space\relax                 % kill next space if token is "("
    \else
      \let\sx@space\;
    \fi
    \let\sx@next\sx@scan                  % scan next token
  \fi\sx@next
}
\newcommand{\sexp}[1]{\let\sx@space\relax\sx@scan#1\relax}
\makeatother

\begin{document}
$\sexp{+ (\times 5 3) (- 6 4 {7 8})}$
\end{document}

Note that you can also group elements, like {7 8} to momentarily switch off the effect of the command (i.e. it shows as "78" in the output). You might also need this if some symbol in the expression is a complicated macro that takes arguments or whatever, just enclose the whole thing in a single {group}.

enter image description here