[swift-evolution] Proposal: An Either Type in the STL

Matthew Johnson matthew at anandabits.com
Sat Dec 12 12:58:25 CST 2015

> A structural sum type that was a disjoint sum and strictly ordered seems reasonably easy to support, if not perfectly ergonomic, and would handy if we ever get variadic generics, and better than the Either towers Haskellers construct for abstract anonymous sums. You could say that (T | U | V) behaves like an enum with cases .0(T), .1(U), .2(V); maybe you get implicit conversion in cases where the type-to-tag association is unambiguous. (T | T | U | V) and (U | T | V) would be distinct types, just like (T, U, V) and (U, T, V) are distinct product types.

Did you mean "(T | U | V) and (U | T | V) would be distinct types, just like (T, U, V) and (U, T, V) are distinct product types."?

In the typed throws with multiple error types use case I think most developers would intuitively expect all permutations of error types to mean the same thing:
()->() throws T, U, V
()->() throws U, T, V

I haven't given a lot of thought to other use cases but I my instinct is that the same intuition would apply.  I'm not sure that order provides a meaningful distinction for structural sum types.  I would like to learn about any use cases where the distinction would be meaningful if anyone knows of any.

If order doesn't provide a useful and meaningful distinction or if it contradicts intuition in the most prevalent and compelling use cases maybe syntactic permutations should be irrelevant.  A projection of syntax to a canonical order could be performed such that (U | T | V) is projected to (T | U | V) and the type system never encounters any of the other permutations.  

If we do this we probably don't want to expose cases of .0(T), etc as the canonical order be an implementation detail.  The constituent types of the union type would naturally be subtypes of the union type so dynamic cast could be used for projection instead. 


More information about the swift-evolution mailing list