Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Filtered collection type inference #1177

Open
pointlessone opened this issue Jun 22, 2024 · 1 comment
Open

Filtered collection type inference #1177

pointlessone opened this issue Jun 22, 2024 · 1 comment

Comments

@pointlessone
Copy link
Sponsor

Suppose we have the following code:

class Cat
  # ...
  def meow
    # ...
  end
end

def Dog
  # ...
  def bark
    # ...
  end
end

And here's how we might use it:

# pets: Array[Cat | Dog]
def cat song(pets)
  cats = pets.select { |pet| pet.is_a?(Cat) && pet.awake? }
  cats.each do |cat|
    cat.meow # Error here
  end
end

Steep is having issue with this code:

Type `(::Cat | ::Dog)` does not have method `meow`

I guess, this can be justified by the type definition of Array#select but this is not exactly useful. Filtering is used all the time to narrow down collection to a subset with certain properties and type is often that property.

Is there a way to narrow down the type of the collection? Or do I have to rewrite it with next unless pet.is_a?(cat) in the each` block?

@ParadoxV5
Copy link
Contributor

ParadoxV5 commented Sep 29, 2024

If blocks can have overloads – ideally with ruby/rbs#1875, then RBS can guide type checkers on this type narrowing.
Take Enumerable#reject for a nice example:

  def reject: () [F < Elem] { (F) -> false?
                            | (Elem) -> boolish } -> Array[F]
            | () -> ::Enumerator[Elem, ::Array[Elem]]

Relevant methods:

  • detect/find (Enumerable)
  • find_all (Enumerable)
  • partition (Enumerable)
  • take_while/drop_while (Enumerable, Array)
  • filter/select/reject (Enumerable, Array, Hash, Struct, ENV, DBM)

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

No branches or pull requests

2 participants