Question

I'm constantly trying to acquaint myself with different programming concepts, and I recently looked deeper into ranges.

In Haskell a range is basically a literal that expand to some kind of array.

In Ruby (and Python I guess) it is a completely different type.

My question: What are use cases for ranges except iterating over them like an array?

Était-ce utile?

La solution

Ranges are mathematical objects that far predate programming and arrays. What you can do with a Range is check whether or not a value lies within a Range.

Iterating over a Range is not the primary use case; in fact, for a lot of Ranges, it isn't even possible. E.g. for a Range of real numbers, you cannot iterate over it because there is no such thing as as the "next real number": whatever possible real number you pick as "the next one", there are still infinitely many real numbers between the current and the "next".

In Ruby, the Range protocol is split in two: membership checking and iterating. Objects that are used as endpoints in Ranges MUST implement the membership checking portion of the protocol and MAY additionally implement the iteration part of the protocol.

The membership part of the protocol is simple: both the start and the end object must respond to the <=> message (the standard combined comparison method which returns -1, 0, 1, or nil for objects that are less than, equal, greater than, or incomparable). For the iteration part, the start object also needs to respond to the succ message (and the object it returns needs to respond to succ and so on …).

It is perfectly possible in Ruby to, for example, construct the following Range of Rational numbers:

r = 1r..10r

I can check membership:

r.cover?(5r) #=> true

But not iterate:

r.to_a
# TypeError: can't iterate from Rational
Licencié sous: CC-BY-SA avec attribution
scroll top