Hacker News new | ask | show | jobs
by pwm 1537 days ago
Sum types are one of those things missing from most mainstream languages that people don't even realise that they are deprived of something fundamental. They naturally complement product types that are ubiquitous in most/all languages.
3 comments

Specifically, closed sum types. You can usually get open sum types by way of inheritance.
True that! It was eye opening once I understood that! Here's a basic type system I made in Python for a small smart contract language compiler I'm working on. It works with mypy pretty flawlessly! [1] I still haven't figured out how to prevent subclassing with methods that don't comply with a specific type signature, but that's a story for another day...

[1] https://yourlabs.io/pyratzlabs/pymich/-/blob/master/pymich/m...

C++17 has std::variant<> and it's ubiquitous in my code. Catching your type errors at compilation time is something you don't have to give up any more after doing your prototyping in Haskell.
it is very clunky though. there is no pattern matching support — you need to write non-trivial visitors to do any meaningful work and it takes the fun out of it. imo, Rust gets it right and borrows a lot of Haskell ergonomics
It's easy to combine a list of per-type visitors, perhaps with an "auto" catch-all, into a single visitor for use with visit(), though. Not as fun as Haskell but a real improvement over C++14 and good enough for sum types in production C++.

See struct visitors in https://github.com/llvm/llvm-project/blob/main/flang/include...

FreePascal supports them, via variant records. A nice gain in developer-friendliness over C.