Hacker News new | ask | show | jobs
by overlisted 1378 days ago
I don't understand this one :

> No space before the colon in type annotations in the default formatting.

Why do people like that kind of syntax? I know it's more symmetrical, but what personally bothers me is that it's grammatically incorrect. We're already used to placing colons right after words, so why change it?

1 comments

Ah! that's a really good question. No whitespace before the colon in type annotations is my own personal pet peeve – the hill I'd die on – so it seems like my duty to answer.

I think of it this way: there are two symbols that by coincidence are written the same way (two dots aligned vertically). I mean that genuinely (I think of them as separate things), but it also helps as an explanative device.

The first I'll call the prefatory colon. Its usage matches usage in English [1], where the text preceding the colon introduces the text after the colon. For example, it is used to start a block (as in Python), or to create a key-value pair (as in Python), or define a member of a struct with a name-value pair (as in C or Rust).

The second is the type annotation. This syntax is borrowed from mathematics (notably, type theory). It is a binary relation, and binary relations are always written with equal space on the left and right. Just as you'd never write `x= 1` (another relation), `x> y` (relation), or `x+ z` (operator), you'd never write `x: X`.

Whenever I see "a: b", I immediately think prefatory colon. Despite having seen it hundreds or thousands of times in other people's code, it always trips me up when it turns out to be a type annotation, which has to be deduced from context or the right-hand side.

Truthfully, I'm somewhat baffled how it would ever even cross anyone's mind when designing a language to write type annotations like `x: X` given the long-established, pre-existing precedent in mathematics and the way its semantics seem backwards (if you had to use a prefatory colon, `X: x` would make much more sense to me).

[1] https://en.wikipedia.org/wiki/Colon_(punctuation)#Usage_in_E...