Skip to content

Better union-union subtyping#531

Merged
soutaro merged 1 commit intomasterfrom
filter_map
Apr 6, 2022
Merged

Better union-union subtyping#531
soutaro merged 1 commit intomasterfrom
filter_map

Conversation

@soutaro
Copy link
Owner

@soutaro soutaro commented Apr 6, 2022

Subtyping between union types can be improved by skipping common types. This happens on #filter_map.

Assume the following type definition:

class Array[Element]
  def filter_map: [T] () { (Element) -> (T | nil | false) } -> Array[T]
end

and a Ruby code

[1, 2, 3].filter_map do |i|
  if i.odd?
    i.to_s
  end
end

We want the type of the expression to be Array[String], but it returns Array[String | nil]. A subtyping check happens with String | nil <: T | nil | false, and was solved to T == String | nil.

The hack is to try types without type variables before types with type variables.

  1. nil <: T | nil | false tries nil <: nil and nil <: false before nil <: T.
  2. The nil <: nil holds, and the later nil <: T isn't tried.

And we have Array[String]! 🎉

@soutaro soutaro enabled auto-merge April 6, 2022 12:18
@soutaro soutaro merged commit f7b75a5 into master Apr 6, 2022
@soutaro soutaro deleted the filter_map branch April 6, 2022 12:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant