Hacker News new | past | comments | ask | show | jobs | submit login

It sometimes feels like there is a strange resistance to defining ad hoc sum types. If your language has good pattern matching capabilities and an expressive syntax for declaring data types, then this scales very well.

For example in a pseudolanguage:

    data FooResult = Number | Error
    def foo(n: Number): FooResult = ...
    foo(42) match {
      case n: Number => print(n + 1)
      case e: Error => // handle error case
    }
This gets you very far most of the time. If the tag overhead matters (which should largely only matter in a hot loop), then try to refactor so that the hot loop doesn't error out.

Granted in many languages the above cannot be expressed succinctly and is often avoided for this reason.






That looks more like ad hoc union types than sum types. What happens if you do:

    data FooResult = Number | Number
If you can't distinguish the two cases, then it means they're not an actual sum type, since e.g. the set size is |FooResult| = |Number| whereas a sum type should have 2*|Number|.

The reason ad hoc union types are avoided in Hindley-Milner (HM) languages is that their usability depends on subtyping, which is incompatible with HM. You could get around this by saying that ad hoc sum types require the types to be distinct, but this would greatly impede usability. For example:

    ErrorA = FileNotFoundError | ParsingError
    ErrorB = FileNotFoundError | PermissionError
    ErrorC = ErrorA | ErrorB // Oops, trying to ad hoc sum FileNotFoundError twice
The tried and true solution in HM is to use generic types like Result<A,B>, where you separate the cases with labels Ok and Err.

On the other hand, languages with subtyping aren't that averse to ad hoc union types. TS and Python already have them and C# is adding them soonish [1].

[1] https://github.com/dotnet/csharplang/blob/main/proposals/Typ...




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: