Alter arguments in custom command
Well, you can do it with much shorter code using xparse
. No need of if then, we simply use the \str_case_e:nnF
macro from expl3
.
Edit: As Manuel mentioned in the comments, it is better to grab the first item of the input by running the helper without braces. Then C^*
also gets converter into \mathbb{C}^*
. The obvious reason for splitting into cases, would be if some was to use \mathbb
others \mathcal
etc.
\usepackage{xparse}
\ExplSyntaxOn
\NewDocumentCommand\funcHelper{m}{
\str_case_e:nnF { #1 }
{
{N}{\mathbb{N}}
{Z}{\mathbb{Z}}
{Q}{\mathbb{Q}}
{R}{\mathbb{R}}
{C}{\mathbb{C}}
{K}{\mathbb{K}}
{F}{\mathbb{F}}
}{
#1
}
}
\NewDocumentCommand\func{mmmm}
{
\arraycolsep=1.5pt
\begin{array}{rl}
#1
:
\funcHelper#2
& \longrightarrow
\funcHelper#3
\\
x & \longmapsto #4
\end{array}
}
\ExplSyntaxOff
Daleif's answer is very pretty and is a really nice demonstration of the power of LaTeX3! On the other hand, I prefer a minimalist approach:
\documentclass[a4paper]{article}
\usepackage{amsmath,amsfonts}
\usepackage{array}
\newcommand\func[3]{%
\begin{array}{r@{}l}
#1\colon{\mathbb #2}&\longrightarrow{\mathbb #3}\\
x&\longmapsto #1(x)
\end{array}%
}
\begin{document}
$\func{f}{R}{C}$
$\func{f}{R}{C^*}$
\end{document}
This produces:
A few comments:
- The fourth argument in the OP is redundant as it is the same as
#1
- The first character in
#1
and#2
will be typeset in\mathbb
, whether or not this makes sense but this fits with all of the examples in the OP so I think that's OK - I didn't know about
\longmapsto
so this question was useful to me! - It is better to use
\colon
than:
- I added
@{}
to thearray
to gobble some extra space before the arrows
Edit
Using xparse you can have an optional fourth argument, that defaults to #1
:
\documentclass[a4paper]{article}
\usepackage{amsmath,amsfonts}
\usepackage{xparse}
\usepackage{array}
\NewDocumentCommand\func{ mmm O{#1}}{%
\begin{array}{rl}
#1\colon{\mathbb #2}&\longrightarrow{\mathbb #3}\\
x&\longmapsto #4(x)
\end{array}%
}
\begin{document}
$\func{f}{R}{C^n}$
$\func{f}{R}{C^*}$
$\func{f}{R}{C^*}[g]$
\end{document}
This produces:
It is slightly non-standard having the default argument at the end, so you might want to use
\NewDocumentCommand\func{ O{#2}mmm }{%
\begin{array}{rl}
#2\colon{\mathbb #3}&\longrightarrow{\mathbb #4}\\
x&\longmapsto #1(x)
\end{array}%
}
instead but I would put the optional argument at the end as this looks more natural to me.