Add Range
type for representing intervals of values.
#190
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.
This PR introduces the
Range
type, a generic interface for representing value intervals.The
Range
type is particularly useful for working with and enforcing boundaries of acceptable values. It can also be used as a shorthand for creating linear enumerations, though it is not optimized for this case.From the docs on the
Range
type itself:The only values stored by a Range are the lower and upper bounds. The values within the interval are calculated lazily, and only when necessary. With the exceptions of
#each
and#reverse_each
, most methods are implemented using only comparisons between these bounds.As Myst does not currently provide a literal syntax for Ranges, creating a new Range is done with normal type instantiation, providing the first and last values of the Range as arguments:
%Range{10, 20}
.Any value type can be used in a Range so long as it implements the
<
and<=
comparison operators. However, to enable iterating through the Range, value types must also implement a #successor that returns the next element of the interval.Ranges can also be used in reverse (e.g., with
#reverse_each
) if the value type defines a #predecessor method returning the previous element of the interval.Range includes
Enumerable
, so all of Enumerable's methods can be used directly on Ranges. Where possible, Range provides optimized implementations of Enumerable methods to avoid having to iterate all values in the interval (e.g.,#includes?
).