Re:Tagged Unions Are Overrated
by mamcx on Friday February 19, 2021 @09:14AM
(#26193340)
The problem with unions/enums is that is hard to pick a subset or superset of them, despite it will be not hard to add to any language. Is similar to projection on the relational model (aka:select), sometimes I need:
And other times:
This is analog to structs, where eventually is "discovered" that is nice to:
But somehow enums are still considered second-class in the algebraic type space.
[ Parent
| on HN ]
Re:Tagged Unions Are Overrated
by Ari_Rahikkala on Friday February 19, 2021 @09:54AM
(#26193782)
I used to think that this was only ever going to be possible with some sort of incomprehensible type trickery that I would never be able to understand. Then TypeScript came along and showed me that no, actually, in a structural type system, it's just about as simple as you could imagine:
type Foo = { kind: 'A', aItem: number } | { kind: 'B', bItem: string } | { kind: 'C' };
type SubsetFoo = Foo & { kind: 'B' | 'C' }
type SupersetFoo = Foo | { kind: 'D', dItem: boolean };
I'm sure there are imperfections here. For a start, SubsetFoo's normalized form looks rather ugly when you mouse over it in VSCode. But it does get you the niceties of exhaustiveness checking and type-aware suggestions with control flow awareness, etc..
Re:Tagged Unions Are Overrated
by skjfdoslifjeifj on Friday February 19, 2021 @11:44AM
(#26194938)
I believe you can get a better normalized form of SubsetFoo by instead doing:
type SubsetFoo = Extract<Foo, { kind: 'B' | 'C' }>;
Re:Tagged Unions Are Overrated
by colanderman on Friday February 19, 2021 @10:30AM
(#26194164)
OCaml has this for unions, see Polymorphic Variant Types here: https://www.ocaml.org/releases/4.11/htmlman/types.html
Scala and TypeScript have (partial) answers to this.
In your example, Scala 2 would let Int32 and Int64 inherit a trait that Str doesn't. TypeScript would let you write a union type Int32 | Int64 that doesn't include Str (or add ExtraValue), and I think Scala 3 will have something very similar.