Allow unions of same-type containers for certain container methods #10510
+166
−51
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
The following fails to compile, even though it should have a well-defined result:
This happens because
Array(T)#+(other : Array(U)) forall U
ensures only thatself
is never a union of arrays, butother
in general could be one; thus, following the discussion from #8973, it is correct to issue a compiler error here (althoughU
shouldn't even be substitutable in the first place). The solution is to remove the unnecessary free var in theother
's restriction, which works for most methods affected by this PR. They are:Array#&
Array#|
Array#+
Array#-
Array#product
(Move Array#product to Indexable#cartesian_product #10013 does not have the same free var anymore)Deque#+
Hash#merge
(both block and non-block overloads)Set#|
Set#+
Set#^
(relies onEnumerable#first_internal
copied from MakeArray#transpose
,Enumerable#reject
,Enumerable#to_h
work with tuples #10445)In the example above, this makes
typeof(foo + foo)
always equal toArray(Int32 | Char)
, instead ofArray(Int32 | Char) | Array(Int32) | Array(Char)
. However this trick doesn't work withTuple#+
andNamedTuple#merge
, because even though these types have built-in covariance, the types with different arities / names still cannot be merged. Those two methods are fixed instead by dispatching over the other argument's type. In other words:Note that #10429 disallows unions inside splats, so
a + b
supports more types than{*a, *b}
(it already does sincea
can already be a union ofTuple
s).