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


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?

  • 2
    Just a thought: this is actually a question about preserving spacing in math mode, so it might help if you edit the title to reflect that. The fact that you're doing it because of prefix notation doesn't matter so much. – David Z Jul 30 '10 at 8:01
  • 2
    I think the title is fine. I'd rather have questions about high level topics (e.g prefix notation or s-expressions), rather than low level details (which may or may not be the answer to the question). People will probably search by topics. – Juan A. Navarro Jul 30 '10 at 8:30
  • "Typesetting expressions in prefix notation"? – user7 Jul 30 '10 at 12:50
  • 2
    BTW, if you're formatting code, you should use an environment for displaying code verbatim (e.g. verbatim or listings), not math mode. – ShreevatsaR Jul 30 '10 at 14:43
  • The whole point of prefix notation is that you don't need the parentheses. so why do you have them? – Seamus Nov 15 '11 at 11:13

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

  \def\sx@arg{#1}%        save the current token
  \ifx\sx@arg\sx@stop   % is it the end of the list?
    \ifx\sx@arg\sx@close\else\sx@space\fi % add space unless token is ")"
    {\sx@arg}%                            % write the token
      \let\sx@space\relax                 % kill next space if token is "("
    \let\sx@next\sx@scan                  % scan next token

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

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

  • 1
    If there isn't a s-expressions package, would you consider turning this code into one and uploading it to CTAN? – Seamus Aug 24 '11 at 13:40

I would just define a macro \newcommand{\prefix}[3]{#1\;#2\;#3}, and then use it like this:


Is it readable enough is a personal preference.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.