5 ms·
Sum types are a fundamental feature of the type system, just like product types. C++ doesn't try to implement the concept of struct as a library abstraction, ei
by Sharlin 1y ago
Sum types are a fundamental feature of the type system, just like product types. C++ doesn't try to implement the concept of struct as a library abstraction, either. Or the `||` operator for that matter, even though it's always expressible with just `!` and `&&`.
- fooker 1y agoAbout product types, C++ does try to implement that as a library too (std::tuple), and the result is equally disastrous :) I don’t really disagree with you, but consider that one of the main goals of an object oriented language is to allow you to define custom types.
- Sharlin 1y agoSure, but my point was that user-defined nominal sum types (tagged unions such as Rust enums) are just as important as user-defined nominal product types (structs, records, classes). The concept of "one of these" is just as important as "all of these" in domain modeling. Proper support for algebraic data types is a force multiplier. OOP chose to implement "one of" with subclasses and runtime polymorphism, but that's not really "one of these choices" but "one of an arbitrarily large space of choices" because OOP interfaces are extensible by design. You can add support for "sealed" interfaces, but at that point you basically have tagged unions with a very clumsy syntax (and bad performance depending on your object model). C, of course, has `union`, which is what you'd expect from C: a very basic, very error-prone building block for DIY tagged unions. C++ improved (depending on who you ask) on C structs by adding privacy control, methods, and so on. Similarly C++ should improve on C unions by adding implicit tagging, soundness, exhaustivity analysis and so on, so that nobody has to write `class X { enum { a_, b_ } tag; union { A a; B b; }; }` and all the associated ceremony ever again.
- fooker 1y agoThe tagging part is easy, the tricky thing is to unify this concept with constructors and destructors. Like Haskell, you’d want different tags to be constructed by different constructors. But it’s unclear how this will integrate with destructors, RAII, and inheritance.