What are intervals?
An interval is a sequence of values of the
same type between a given pair of endpoint values. Gosu provides native
support for intervals. For instance, the set of integers beginning with
0 and ending with 10 is an integer interval. This interval contains the
values 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10. The Gosu syntax for this set
of integers is 0..10.
Intervals are particularly useful for concise, readable for loops.
For example, consider this concise, readable code:
for (i in 0..10) {
print("The value of i is " + i)
}
This code prints the following:
The value of i is 0
The value of i is 1
The value of i is 2
The value of i is 3
The value of i is 4
The value of i is 5
The value of i is 6
The value of i is 7
The value of i is 8
The value of i is 9
The value of i is 10
This code replaces the more verbose and harder-to-read design pattern:
var i = 0
while( i <= 10 ) {
print("The value of i is " + i)
i++
}
Intervals do not need to be numbers. Intervals can
be of many types including numbers, dates, dimensions, and names. Gosu
includes built-in shorthand syntax with a double period (..) for intervals for dates and
common number types, such as the previous 0..10 example. The built-in shortcut
works with the types Integer,
Long, BigInteger, BigDecimal, and Date. All
decimal types map to the BigDecimal
interval.
You can also add custom interval types
that support any type that supports iterable comparable sequences. You
can then use your new intervals in for
loop declarations.
If you need to get a reference to the
interval’s iterator object (java.lang.Iterator),
call the iterate method,
which returns the iterator.
Omitting an initial or ending value
In the simplest case, a Gosu interval
iterates from the beginning endpoint value to the ending endpoint value,
including the values at both ends. For example, 0..5 represents the values 0,
1, 2, 3, 4, 5.
In some cases, you want to exclude the beginning value but you still want your code to show the beginning value for code legibility. In other cases, you want to exclude the endpoint value from the interval.
If omitting the initial or ending value results in an empty set of values, iterating over the interval does not occur.
To exclude an endpoint in Gosu, type the
pipe "|" character:
- To omit the value of the starting endpoint, type the pipe character after the starting endpoint.
- To omit the value of the ending endpoint, type the pipe character before the ending endpoint.
- To do make both endpoints open, type the pipe character before and after the double period symbol.
Compare the following examples:
0..5represents the values 0, 1, 2, 3, 4, 5.0|..5represents the values 1, 2, 3, 4, 5.0..|5represents the values 0, 1, 2, 3, 4.0|..|5represents the values 1, 2, 3, 4.0..|0does not iterate.0|..|1does not iterate.
See also
