3 ms·
The union part is just an (obvious) optimization. An implementation detail. Sum types are not required to use a union; they can be implemented without using a u
by cornstalks 4y ago
The union part is just an (obvious) optimization. An implementation detail. Sum types are not required to use a union; they can be implemented without using a union.
- zabzonk 4y agohow, exactly?
- cornstalks 4y agoBy using a struct with lazily initialized members, for example.
- zabzonk 4y agoif that is your example, provide some code.
- cornstalks 4y agoPretend we have the following sum type: enum SumType { Foo(foo), Bar(bar), Baz(baz), } void DoSomething(SumType sum_type) { match sum_type { Foo(foo): foo.do_x(); Bar(bar): bar.do_y(); Baz(baz): baz.do_z(); } } This could be lowered to: struct LoweredSumType { optional<Foo> foo; optional<Bar> bar; optional<Baz> baz; } void DoSomething(LoweredSumType sum_type) { if (sum_type.foo.has_value()) { sum_type.foo->do_x(); } else if (sum_type.bar.has_value()) { sum_type.bar->do_y(); } else { sum_type.baz->do_z(); } } This isn't real code; it's a pretend language that's kind of a mix of Rust and C++. But it illustrates that the sum type can be lowered into a non-union representation.
- zabzonk 4y ago> Pretend we have the following sum type: which looks remarkably like a union to me, if i understand your made-up language.
- cdcarter 4y agoIt's not a union, though, it stores references to three memory locations, not just one (as a union represents a single memory location which can have multiple possible interpretations). And the lowered code has nothing protecting it from an invariant where more than one reference is non-null!
- the-smug-one 4y agoWhy does the members be lazily init:ed?
- cornstalks 4y agoIf the data types have constructors and/or destructors that have side effects then it has to be lazy. Otherwise IMO it's not really behaving like a sum type.
- the-smug-one 4y agostruct List {}; struct Cons : public List { Cons(int v, List* nxt); int v; List* nxt; }; struct Nil : public List {}; This is how you'd do it in Java.
- zabzonk 4y agoand you would use it ... how?
- deleted 4y ago[deleted]
- dcow 4y agoIt's not exactly Java, but: Cons(1, Cons(2, Cons(3, Nil)))
- kaba0 4y agoActually, Java does have sum types nowadays, and you can write a recursive list implementation like “new Cons(2, new Cons(3, Nil.nil()))”. Here is a definition for a Maybe type, converting it to a List is left as an exercise to the reader :) : https://news.ycombinator.com/item?id=35133670 https://news.ycombinator.com/item?id=35133670
- dcow 4y agoI just meant because I was eliding the `new`s.
- the-smug-one 4y agoI've showed you an alternative encoding, maybe get to work and learn something yourself?