Hacker News new | ask | show | jobs
by thaumasiotes 1237 days ago
> Is "x- 20" the same as "x - 20" the same as "x -20"[?] In the vast majority of modern programming languages, that is a yes.

Is that really true? I wouldn't exactly feel comfortable with "x -20", though I suspect you're right about at least a large number of languages determining the meaning of the hyphen through local syntactic context ("I just saw an identifier; that must be a non-unary hyphen").

Now I'm interested in whether the corpus of existing code shows any bias between "y = -x" (perfectly allowed, I think) and "y = -1 * x".

1 comments

Distinguishing unary minus from binary minus is not done by spacing in parsers. Most modern language parsers ignore whitespace except where it would cause the concatenation of two identifiers (or in the case of languages like python or nim, where it is at the beginning of a line).

I know this for a fact since I've studied their grammars.

Infix notation and - are really the reasons why nobody does this, some people like to use spacing to indicate precedence too (writing code such as "a - 1*g") so it would break some workflows and realistically having a language which is whitespace agnostic except for identifiers AND the minus operator just seems too irregular for people to commit to it.

Depends on the parser. See e.g. [0] for Elm's take on it: it already had special logic for differentiating "(.)" and "( . )".

[0] https://elm-lang.org/news/0.9

That's why I said most. Obviously there exist languages, such as elm, where this is not the case, but in the case of those languages, the teaching literature (as is the case with elm) explains these things. Most languages don't do this precisely because their designers made the judgement call that the additional parsing complexity (both for the actual parser and the human) outweighed the benefits of allowing you to have minuses in identifiers.