[Tex/LaTex] Function like macro


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.,


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):


(In fact, TeX has \ifnum:



And can be invoked:


And nested:

Related Question