[Tex/LaTex] Function like macro

tex-core

If you have programmed in a high level programming language, you must be familiar with the concept of functions, subroutines which return a value. For example, if you write in C, you can write a function to compute the absolute value of an integer parameter

int abs(int a) { 
    return a > 0 ? a: -a; 
}

You can invoke this function, assigning its result to a variable, by writing e.g.,

int v = abs(a)`

Furthermore, you can use the returned value directly, without assigning it to a variable, e.g.,

abs(abs(a)-abs(b))

What's the closest you can get to this with TeX programming? The challenge is in minimizing the coupling between the caller and the callee. Of course, since TeX is primarily about characters and textual tokens, a more natural example would be something of the sort of the chain of function calls in:

int ispalindrome(const char *s) {
   return strcmp(s, strrev(s)) == 0;
}

Best Answer

From a computer science point of view, macros are functions. The issue here is rather that TeX doesn’t offer many maths and string processing directives. But assuming we had these functions, your abs function could be directly translated into a macro definition (either TeXish or LaTeXish):

\def\abs#1{%
  \ifgreater{#1}{0}{#1}{\neg{#1}}}

(In fact, TeX has \ifnum:

\def\abs#1{%
  \ifnum#1>0\relax#1\else\neg{#1}\fi}

)

And can be invoked:

\abs{42}

And nested:

\abs{\minus{\abs{a}}{\abs{b}}}
Related Question