by pdpi Β· 4y ago Β· 0 comments
ADTs + pattern matching are the killer feature set that makes the more popular functional languages so damn pleasant to use, and they're starting to spread to more and more languages. I suspect that, 50 years from now, we'll look back and see them as the key paradigm shift of this era.
Turns out that having a much better tagged union opens up so many possibilities. Software deals with states and what's better to represent states than an ADT? Last time I was fixing an issue where a mouse position is initialized to (0.0f,0.0f) and causes it to trigger a mouse event on startup. The fix was to simply turn it into an Option<(f64,f64)> which is so much better than initializing them as (-1.0f,-1.0f) because it forces you to check all the places where you do arithmetic operations on them.
Blub. It's one of those conceptual steps which seems to have no benefit until it actually clicks and you realise how much it opens or does. Being a tremendously good educator is necessary to make people take that step without experience.
Is an Algebraic Data Type (ADT) in rust an enum or tuple? I make heavy use of enums (along with structs) as my program foundations. Am I using ADTs?
The third type the query shows are unions, which I'm not familiar with.
It's the combination of both.
Tuples are Product Types. If you treat types as sets of values, then the type (A,B) is the cartesian product of types A and B. For all practical purposes, structs are just syntactic sugar for tuples. Enums are Sum Types. The values of Result<T, E> are fundamentally just all the values of T plus the values of E (with a tag to tell them apart). Put the two things together, and enum Coordinates{TwoD(f32, f32), ThreeD(f32, f32, f32)} is a set of values with cardinality #f32^2 + #f32^3. You can build types corresponding to arbitrary polynomials, hence the name.
"Union type" usually just means the same as "sum type", though it can also be used to mean C-style unions specifically.
(There's also functions as exponential types, with A -> B having cardinality #B^#A, but you're neck deep in type wankery when you start talking about those :o)
Almost every language supports product types in some way, either implicitly or explicitly, and nobody really bothers talking about those in isolation. It's when you add sum types to the mix that people start talking about ADTs, and it's when you add pattern matching that the whole thing comes into its own and you can just express functions as "things with this shape become things with that shape".
π΄ + π΄ β π΄
π΄ βͺ π΄ = π΄
This is a good explanation: https://jrsinclair.com/articles/2019/algebraic-data-types-wh...
But theyβre additionally great because the compiler does exhaustive pattern matching.
You mean the key paradigm shift of the 1970s when they were invented. Only took 50 years for it to go semi-mainstream.
OOP was invented in the 60s/70s, but the paradigm shift came in the 80s/90s.