Parsing absolute value signs: Does $|x|x|x| =|x|\cdot x \cdot |x|$ or $ {\large|} x\cdot |x| \cdot x{ \large |}$?

233 Views Asked by At

I am writing an equation parser for fun and I kinda thought parsing absolute value signs would be like parsing ordinary bracktets - but this is not so as there is no 'open' or 'close' version of $|$. In particular there are two potential interpretations of the expression $$ |x|x|x|,$$ namely $$ |x|x|x| = |x|\cdot x \cdot |x| = x^3,$$ or $$|x|x|x| = {\large|} x\cdot |x| \cdot x{ \large |} = |x^3|. $$

I think there is no agreed upon convention that determines which one of these should be correct. But I was wondering if there are any best practices that we can give some kind of arguments for.

I realize that the expression $|x|x|x|$ looks ridiculous, but we can also have for example $$ |x|f(x) + g(y)|y| . $$ I would certainly parse this as $(|x|f(x)) + (|y| g(y))$ but who am I to say it does not equal $|x \cdot |f(x)+g(y)| \cdot y|$.

Edit: The parser I wrote already accepts $\operatorname{abs}(x)$ and the like. But I want to allow the user to write the very natural $|x|$ as well. But then I can't prevent them for also writing $|x|x|x|$, even though this is silly and borderline criminal. So I do have to make some choice on how to handle this and am just wondering if anyone has any preference for one of the interpretations and maybe some reasons :)

3

There are 3 best solutions below

1
On

I would suggest that you make up some rules in which situations multiplication must be written using a dot or asterisk ($3 \cdot 4$ or $3 * 4$) and when they don't. Hopefully these rules make |x|x|x| illegal and require $|x| \cdot x \cdot |x|$.

These rules may be complicated, for example I think 2x is quite acceptable, but x2 isn't (for two times x).

3
On

I think, when you really need to write $|x.|x|.x|$, it's better to prefer $\bigg |x|x|x\bigg |$ or even better $\bigg|x^2|x|\bigg|$. So, in case of $|f(x).|g(x)|.h(x)||$, better use $\bigg|f(x)h(x)|g(x)|\bigg|$.

And, I think, we can keep $|x|x|x|$ as $|x|.x.|x|$ as that's how you read it from left to right. I guess, that is the reason Wolfram prefers this version.

And, if the input is to be typed in by a user, I think, it's better to use $*$ or $\times$ or $\cdot$ (according to where it is being typed) to denote multiplication and maintain clarity.

3
On

As you say there are no open and close versions of $\mid$. That being the case, my first thought would be that the second $\mid$ encountered by the parser should match with the first (unless prioritised with brackets), so $\mid x\mid x\mid x \mid = x^3$.
In my (limited) experience of writing parsers, tokens are best dealt with at the first opportunity.