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

Union and intersection of Ranges #14488

Open
jgaskins opened this issue Apr 15, 2024 · 2 comments
Open

Union and intersection of Ranges #14488

jgaskins opened this issue Apr 15, 2024 · 2 comments

Comments

@jgaskins
Copy link
Contributor

Combined with #14487, it would be useful to have Range methods that, when given another range, would return a new range that contains the union or intersection of both ranges.

For example:

a = 1..5
b = 3..7

a.union(b)        # => 1..7
a.intersection(b) # => 3..5

If there is no overlap between them, I'm not 100% sure what should happen but I feel like returning nil makes sense.

a = 1..5
c = 10..20

a.union(c)        # => nil
a.intersection(c) # => nil

There are probably some other edge cases to work out, as well, such as:

  • what happens when ranges are infinite in one direction?
    • should the union be infinite in that direction?
    • should the intersection use whichever one has a finite value?
  • for ranges like 1...10 and 10..20 where there's nooverlap, but they are adjacent:
    • should the union be 1..20 — the union of adjacent ranges providing continuity
    • should the intersection be nil (or whatever the non-overlap result is deemed to be)?
  • should (1...10).union(1..10) be 1..10?
  • should (1...10).intersection(1..10) be 1...10?
  • any other edge cases?
@ysbaddaden
Copy link
Contributor

I wonder about actual use cases, yet the methods make sense.

@straight-shoota
Copy link
Member

Using nil to signal there's no overlap is a bit nasty because you'll need nil handling in order to do something with the result. I'm not sure what's the best solution. Raising may be an option, but having no overlap is not really exceptional. Theoretically we could also use something like 0...0 to express an empty range. This would be formally correct, but may be a cause for confusion because Range#begin is usually expected to be part of the range.

About the edge cases: Considering adjacency makes sense. x < 10 || x >= 10 is continuous (but no intersection).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants