class Range
inherits List<of int>
"""
Range emulates the behavior of Python's builtin range function. The behavior
differs in the case where the end value is less than the begin value or the
step value is in a nonsensical direction. In Python these cases return an
empty list. Here they will raise an exception.
"""
def init(beginning as int, ending as int, stepBy as int)
require
(beginning <= ending and stepBy > 0) or (ending <= beginning and stepBy < 0)
test
assert Range(0, 0, 1) == []
assert Range(0, 0, -1) == []
assert Range(0, 10, 2) == [0, 2, 4, 6, 8]
assert Range(10, 0, -2) == [10, 8, 6, 4, 2]
try
for i in Range(10, 0, 2)
assert false
catch Cobra.Lang.RequireException
assert true
try
for i in Range(0, 10, -2)
assert false
catch Cobra.Lang.RequireException
assert true
try
for i in Range(0, 10, 0)
assert false
catch Cobra.Lang.RequireException
assert true
body
if stepBy > 0
for i = beginning .. ending ++ stepBy
.add(i)
else
for i = beginning .. ending -- -stepBy
.add(i)
def init(beginning as int, ending as int)
.init(beginning, ending, 1)
class XRange
implements IEnumerable
"""
XRange emulates the behavior of Python's builtin xrange function. The behavior
differs in the case where the end value is less than the begin value or the
step value is in a nonsensical direction. In Python these cases return an
empty generator. Here they will raise an exception.
"""
var _beginning as int
var _ending as int
var _stepBy as int
def init(beginning as int, ending as int, stepBy as int)
require
(beginning <= ending and stepBy > 0) or (ending <= beginning and stepBy < 0)
test
for i in XRange(0, 0, 1)
assert false
for i in XRange(0, 0, -1)
assert false
c = 0
for i in XRange(0, 10, 2)
assert i == c
c += 2
c = 10
for i in XRange(10, 0, -2)
assert i == c
c -= 2
try
for i in XRange(10, 0, 2)
assert false
catch Cobra.Lang.RequireException
assert true
try
for i in XRange(0, 10, -2)
assert false
catch Cobra.Lang.RequireException
assert true
try
for i in XRange(0, 10, 0)
assert false
catch Cobra.Lang.RequireException
assert true
body
_beginning = beginning
_ending = ending
_stepBy = stepBy
def init(beginning as int, ending as int)
.init(beginning, ending, 1)
def getEnumerator as IEnumerator
if _stepBy > 0
for i = _beginning .. _ending ++ _stepBy
yield i
else
for i = _beginning .. _ending -- -_stepBy
yield i