5 ms·
"Algebraic data types" refers to having both product and sum types, where products are the records/structs that just about every language has, and sums are inde
by Twisol 6y ago
"Algebraic data types" refers to having both product and sum types, where products are the records/structs that just about every language has, and sums are indeed the "discriminated unions" under discussion.
Most languages don't have built-in syntax for sum types, so most developers are familiar with sum types only by the shadows cast by a variety of encodings. One of them is the subject of the OP, the Visitor pattern. Another is the "tagged union" seen in C, effectively:
struct Rectangle { int x, y, w, h; }
struct Circle { int x, y, r; }
struct Shape {
enum {
RectangleTag,
CircleTag,
} tag;
union {
struct Rectangle rectangle;
struct Circle circle;
};
};
Which doesn't look too bad until you realize I haven't explained how to use the thing, and then it's similarly involved and even more delicate than the Visitor pattern.
- dboreham 6y agoAh, very interesting thanks. I've seen sum types implemented in terms of inheritance (or fancy modern inheritance such as traits). Doesn't get you exclusive case enforcement, which imho is the thing that's actually useful here.
- kaba0 6y agoSome languages have sealed classes for this reason.