# \newcommand that restricts the value of an argument

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

\newcommand{\R}[1]{\ensuremath{\mathbb{R}^{#1}}}


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?

-

## migrated from stackoverflow.comJun 28 '12 at 19:38

This question came from our site for professional and enthusiast programmers.

Insert $\R{}$ –  Alexey Malistov 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.

\documentclass{article}
\usepackage{xparse}
\usepackage{amssymb}
\ExplSyntaxOn
\cs_new:Npn \my_R:n #1
{
\ensuremath{\mathbb{R}^{#1}}
}
\NewDocumentCommand \R { o }
{
\IfNoValueTF { #1 }
{
\peek_catcode:NTF 1
{
\my_R:n
}
{
\ensuremath{\mathbb{R}}\
}
}
{
\my_R:n {#1}
}
}
\ExplSyntaxOff
\begin{document}
This is \R and this is \R3 and this is \R 4 and here is \R[23].
\end{document}

-
Oh wow, didn't notice that this was such an oldie! –  Scott H. Jun 28 '12 at 20:22
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