This question already has an answer here:

I was wondering how to create a custom command that works something like this:

\mycommand{1} = blue
\mycommand{2} = red
\mycommand{3} = yellow

where any other argument causes an error. Basically, I want to "switch" on the argument, so that each argument has one predefined outcome. I tried doing something like Haskell's pattern-matching, and I have looked at various key-value packages but haven't been able to get a solution from them.

Im sorry if this doesn't make sense, I'm not entirely sure how to put this problem into words.

marked as duplicate by Werner macros Oct 28 '16 at 21:31

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • Will your "predefined argument" be numeric or string? – Werner Oct 28 '16 at 20:52
  • This is pretty vague. Can yo give more details as to what you want. Currently \mycommand does not do anything. You wat it to accept only 1, 2, 3 as valid arguments or blue, red, yellow. pgfkeys, for example, will certainly throw errors if it does not recognise a key – Andrew Oct 28 '16 at 20:54
  • string And I want it to accept 1,2,3 as arguments, as an example – Matt G Oct 28 '16 at 20:56

  \ifcsname foo\detokenize{#1}\endcsname
      \csname foo\detokenize{#1}\expandafter\endcsname
     \PackageError{mypackage}{go away: \detokenize{#1} not defined}{really}%

\expandafter\newcommand\csname foo1\endcsname{ONE}
\expandafter\newcommand\csname foo2\endcsname{TWO}
\expandafter\newcommand\csname foo3\endcsname{THREE}







the above gracefully accepts any argument, making errors such as

! Package mypackage Error: go away: \section +\cos \usepackage  not defined.

See the mypackage package documentation for explanation.
Type  H <return>  for immediate help.

l.24 \mycommand{\section+\cos\usepackage}

  • What if, instead of displaying a string, I want to perform another command, like \includegraphics{}? – Matt G Oct 28 '16 at 21:13
  • @MattG just write \includegraphics{..} instead of TWO it makes no difference to TeX what is in the replacement text of a command. – David Carlisle Oct 28 '16 at 21:20

So here's an example which uses l3keys from expl3. The key somekey is defined to take a number of choices and will throw an error if the argument of \mycommand is not one of the pre-defined choices. The argument of \mycommand is then taken as the value given to the key somekey.


\keys_define:nn { mattg } {
    somekey .choice:,
        somekey / 1.code:n = { Blue },
        somekey / two .code:n = { Red },
        somekey / three .code:n = { Yellow },
    somekey .value_required:n = true 

\NewDocumentCommand \mycommand { m } {
    \keys_set:nn { mattg } { somekey = #1 }

%The argument foo is unrecognised (not being one of the pre-defined choices) and thus throws an error

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