Maybe you know, maybe you don't, but LaTeX offers 4 different mathematical styles. There's displaystyle, textstyle, scriptstyle and scriptscriptstyle. The first corresponds to math in block environments, i.e., in display mode such as in an equation or displaymath environment, the second occurs when typesetting inline math as is the case with $...$ and the third and fourth occur in superscript and multiple superscript. You've (hopefully) noticed that for instance \sum gets expanded differently depending on the current style: in displaystyle the super- and subscript are added above and below of the sum symbol while in textstyle they are placed to the right of it.

You can adapt the way a macro is expanded depending on the style of math that is being typeset at that moment. The \mathchoice macro provides this functionality: \mathchoice{D}{T}{S}{SS} expands to D in displaystyle, T in textstyle and (as you hopefully can guess) S and SS in respectively scriptstyle and scriptscriptstyle.

One possible example of this is a macro providing a function environment to write a function in its two-part notation. An example $$f\colon\mathbb{R}\rightarrow\mathbb{R}^+:x\mapsto x^2.$$

But in displaystyle it would be appropriate to use an array environment to align the domain with the argument and the codomain with the image. The result would be $$f\colon\begin{array}{ccc}\mathbb{R}&\longrightarrow&\mathbb{R}^+ \\ x&\longmapsto&x^2\end{array}.$$

So how to achieve this?

Note the use of \colon, a normal colon in math mode is an operator, e.g., the ideal quotient $\textstyle[I:J].$

For experimentation purposes I've added a \makeatletter, the \function@textstyle command now shouldn't be directly callable for an unknowing user, which is what I wanted to accomplish.

Anyway, the results parse to the two examples I've given, when you call it as \function{f}{\mathbb{R}}{\mathbb{R}^+}{x}{x^2}. The order of arguments is:

1. function name,
2. domain,
3. codomain,
4. argument,
5. image.