When defining a macro, is it possible to restrict the value of an argument, so that if the thing followed it is a number, then it takes it as an argument, but if it is not, then it is just empty.

To be concrete, I defined


for a real vector space, so the \R2 and \R3 give the 2-dim and 3-dim real spaces respectively. But what do I do if I want to input \R only?

  • Insert $\R{}$ Sep 6 '10 at 10:12
  • Welcome to TeX.sx! Your question was migrated here from Stack Overflow. Please register on this site, too, and make sure that both accounts are associated with each other (by using the same OpenID), otherwise you won't be able to comment on or accept answers or edit your question.
    – Werner
    Jun 28 '12 at 19:40

Here is an expl3 "solution". It will fail if you try to type something like \Rt and gobbles spaces so that \R 4 will take 4 as an argument. I'm not sure how a 2 digit superscript could be done using your syntax (no argument), so I added an optional argument in square brackets for that case.

enter image description here

\cs_new:Npn \my_R:n #1
\NewDocumentCommand \R { o }
    \IfNoValueTF { #1 }
            \peek_catcode:NTF 1
            \my_R:n {#1}
This is \R and this is \R3 and this is \R 4 and here is \R[23].
  • Oh wow, didn't notice that this was such an oldie!
    – Scott H.
    Jun 28 '12 at 20:22
  • 1
    I'd much prefer \newcommand\R[1][]{\mathbb{R}^{#1}}, which is easier and has a clearer syntax: \R or \R[2].
    – egreg
    Jun 28 '12 at 20:44
  • @egreg I agree! The asker seemed to want a no argument syntax though \R2 etc. Without defining separate commands for each possible dimension, I couldn't think of an easier way to do it :(
    – Scott H.
    Jun 28 '12 at 21:04

Your Answer

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