[Tex/LaTex] Conditionals in \newcommand

conditionalsmacros

I find myself using the \newcommand macro a lot and apart from having the occasional difficulty with properly defining the optional parameter the macro works well. There is one serious limitation though, which I hope will show itself as being my ignorance rather than a limitation, namely the ability to make the macro definition subject to the particular value of a parameter. A simple example: I find frequent use of the expression {1, 2, …, n} what I call an n-set and am using the following simple macro:

\newcommand{\myNset}{\{1,2,\dots,n\}}

Wouldn't it be helpful if I could pass an integer as parameter, make n its default, and produce {1,2} or {1,2,3) etc. if the parameter happens to be 2 or 3. Certainly beats the clumsy:

\newcommand{\myTwoset}{\{1,2\}}
\newcommand{\myThreeset}{\{1,2,3\}}

etc., which of course is too clumsy to be of use. Where draw the line?, at 10?, at 27?

This may only be a trivial example, but I find applications for such conditional processing of my \newcommand macros time and time again, for instance in connection with creating matrices. It would take my use of LaTeX to whole new level.

By the way, I have read through the relevant pages in the LaTeX Companion, but no luck.

Best Answer

\documentclass{article}
\newcommand\myNset[1][99]{\{1,2\ifnum#1=3 ,3\else\ifnum#1>3 ,\dots,n\fi\fi\}}

\begin{document}

\myNset
\myNset[3]
\myNset[2]

\end{document}

\myNset[0] and [1] are the same as [2]

Related Question