具有预定义参数的自定义命令

具有预定义参数的自定义命令

我想知道如何创建一个类似这样的自定义命令:

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

任何其他参数都会导致错误。基本上,我想“切换”参数,以便每个参数都有一个预定义的结果。我尝试做一些类似 Haskell 的模式匹配的事情,并且我查看了各种键值包,但无法从中获得解决方案。

如果这没有意义,我很抱歉,我不完全确定如何用语言来表达这个问题。

答案1

\documentclass{article}

\newcommand\mycommand[1]{%
  \ifcsname foo\detokenize{#1}\endcsname
      \csname foo\detokenize{#1}\expandafter\endcsname
   \else
     \PackageError{mypackage}{go away: \detokenize{#1} not defined}{really}%
   \fi}



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

\begin{document}

\mycommand{2}

\mycommand{0}

\mycommand{a}

\mycommand{\section+\cos\usepackage}

\end{document}

上面的代码优雅地接受任何参数,但会出现如下错误

! 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}

? 

答案2

下面是一个l3keys使用expl3。键somekey被定义为接受多个选项,如果的参数\mycommand不是预定义的选项之一,则会抛出错误。然后将的参数\mycommand作为键的值somekey

\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn
\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 }
}
\ExplSyntaxOff

\begin{document}
\mycommand{1}
\mycommand{two}
\mycommand{three}
%The argument foo is unrecognised (not being one of the pre-defined choices) and thus throws an error
\mycommand{foo}
\end{document}

相关内容