logoalt Hacker News

Mond_today at 1:06 AM2 repliesview on HN

It's worth pointing out that the two examples that you're writing are actually strictly different, and not just "better syntax for the same thing". (This is assuming `String | Int` works as in Python, and the second example works as in Rust.)

To understand the difference, `String | String` is just `String`. It's a union, not a sum type. There's no tag or identifier, so you cannot distinguish whether it's the first or the second string.

If this sounds pedantic, this has pretty important ramifications, especially once generics get involved.


Replies

JackYoustratoday at 8:04 AM

Hijacking your comment because this is a common point that's made on the superiority of Swift syntax against the union syntax.

At least with |, you're attempting to model the state space. You're saying "this is one of these things." You might get the exhaustiveness wrong, but you're in the right ballpark. As it's normally done right now, the Swift developer with five optional properties is modeling state as "maybe this, maybe that, maybe both, who knows, good luck." which is just worse than a bar. If you need to discriminate explicitly, add a `__kind` field!

ekimekimtoday at 1:45 AM

To provide a concrete example, this bit me in a typescript codebase:

    type Option<T> = T | undefined

    function f<T>(value: T): Option<T> { ... }

    let thing: string | undefined = undefined;
    let result = f(thing);
Now imagine the definition of Option is in some library or other file and you don't realize how it works. You are thinking of the Option as its own structure and expect f to return Option<string | undefined>. But Option<string | undefined> = string | undefined | undefined = string | undefined = Option<string>.

The mistake here is in how Option is defined, but it's a footgun you need to be aware of.