I'm trying to write a macro which automatically adds parentheses to an expression if the argument is composite. Specifically, I would like to define a command for the inner product of two vectors using the $v\cdot w$ notation. So I would define

\newcommand{\inner}[2]{#1\cdot #2}

However, if one argument is a composite expression like \inner{v}{w_1+w_2}, the result should be $v\cdot(w_1+w_2)$. I would like the parentheses to be added automatically. The reason is that at some point later I might decide to switch to angle notation <v,w_1+w_2>, which would make the parentheses unnecessary.

I looked into packages like xstring to test for string length. However, I didn't get it to work with subscript expressions like $x_i$ (where no parentheses should be added).

Is something like this possible?

  • 2
    Welcome to TeX.SX! It's only possible if you can give clear constraints about the sub-expressions that may occur as arguments for \inner. TeX's macro expansion system is Turing-complete, so you cannot decide in general if a term is composite or not. What types of sub-expressions should be supported? – siracusa Jul 30 at 13:17
  • Thank you :-) Well, the most common would be sums and products of variables (which could themselves be defined in macros), so \inner{v,a\theta} should be parenthesized, while \inner{v,\myvar} for \newcommand{\myvar}{x_i} should not – Alexander Schlüter Jul 30 at 14:34
  • Can you explain why Turing-completeness would be a problem? It seems like Turing-completeness would guarantee that we can write a macro \inner which does anything we want (after the expressions in the arguments of \inner are fully expanded) – Alexander Schlüter Jul 30 at 14:40
  • If you restrict your command to fully expandable arguments, I think my comment about Turing-completeness doesn't apply. If we'd also allow arguments that need TeX's execution processor to yield the result, it seems impossible to decide whether the argument results in a single or composite expression. But for most documents this is just a theoretical problem anyway. – siracusa Jul 30 at 15:20
$\inner{v}{w_1+w_2}$ $\inner{w_1+w_2}{v}$
  • OP has also specified that implicit multiplication should get parentheses. But +1. – Teepeemm Jul 30 at 14:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.