Skip to content

Commit f6f25c9

Browse files
committed
Convert range() objects using 'integer_interval' from cd 'interval1'
This issue adds translation for the range() class to the DefaultConverter. Note that a python range(start, stop) does not include the value of stop, whereas the 'integer_interval' symbol does. The converter thus has to add or subtract one. Fixes OpenMath#29.
1 parent 4906aa9 commit f6f25c9

2 files changed

Lines changed: 10 additions & 0 deletions

File tree

openmath/convert.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -259,6 +259,7 @@ class BasicPythonConverter(Converter):
259259
- complex numbers (recursively),
260260
- strings,
261261
- bytes,
262+
- ranges,
262263
- lists (recursively),
263264
- sets (recursively).
264265
"""
@@ -278,6 +279,8 @@ def __init__(self):
278279
r('set1', 'set', lambda *args: set(args))
279280
r('list1', 'list', lambda *args: list(args))
280281
r('complex1', 'complex_cartesian', complex) # this does not work if the arguments are not numbers
282+
r('interval1', 'integer_interval', lambda x,y: range(x, y + 1, 1))
283+
281284
# literals
282285
s = self.register_to_python_class
283286
s(om.OMInteger, lambda o: o.integer)
@@ -311,6 +314,12 @@ def do_set(s):
311314
else:
312315
return oms('emptyset', cd='set1')
313316
t(set, do_set)
317+
def do_range(r):
318+
if r.step != 1:
319+
raise ValueError('Cannot convert %r to OpenMath: Range must have a step of 1. ' % obj)
320+
return om.OMApplication(oms('integer_interval', 'interval1'), [om.OMInteger(r.start), om.OMInteger(r.stop - 1)])
321+
t(range, do_range)
322+
314323

315324

316325
# A default converter instance for convenience

tests/test_convert.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ def test_py_om_py(self):
1515
"", "test",
1616
[], [1,2,3],
1717
set(), set([1,2,3]),
18+
range(1, 12)
1819
]
1920
for obj in testcases:
2021
conv = DefaultConverter.to_python(DefaultConverter.to_openmath(obj))

0 commit comments

Comments
 (0)