[OpenSCAD] RFC: Array/String slicing and half open ranges.

Doug Moen doug at moens.org
Fri Nov 8 12:45:26 EST 2019


On Fri, Nov 8, 2019, at 4:43 AM, gasstationwithoutpumps wrote:
> Why not use the Python conventions for slices?

There are two inconsistencies between the Python syntax for slices, and the OpenSCAD syntax for ranges.

One inconsistency is where the 'end' value is located:
Python slice:
     a[start:end:step]
OpenSCAD range:
     [start:step:end]

The other inconsistency is that Python uses half-open ranges, and OpenSCAD uses closed ranges, for the same syntax.
Eg, Python a[0:10] selects elements 0-9 (the first 10 elements), vs OpenSCAD [0:9] is a 10 element range from 0 to 9 inclusive.

Using these two incompatible conventions in the same language is a recipe for confusion.

On Fri, Nov 8, 2019, at 4:43 AM, gasstationwithoutpumps wrote:
> Putting in something that looks like the Python slice but has
> a subtly different semantics is probably a bad idea.

I agree with this.

In the OpenSCAD2 design document, I proposed to introduce a new syntax for ranges and slices, which would not be confusing to either OpenSCAD or Python programmers.

The original OpenSCAD2 proposal was based on Haskell syntax, but it had some limitations, so what I actually ended up implementing in Curv is:
    start .. end
    start .. end by step
for a range, and
    a[start .. end]
    a[start .. end by step]
for a slice. I also adopted the Swift notation for half-open ranges:
    start ..< end
    start ..< end by step
The word 'by' is a keyword in Curv. This syntax has no visual ambiguity about which field is the 'step' value. The '..' operator is found in many programming languages, and it means a closed range, not a half-open range. So this syntax has no ambiguity about closed vs half-open.

There is a design flaw in OpenSCAD range syntax. [0:len(a)-1] is a common idiom for a range containing all of the array indexes of 'a'. However, if 'a' has zero length, then instead of the empty range, you get [0:-1], which is a two element range equivalent to [-1,0]. I think this is a bug that should be fixed, but instead of fixing the bug, this behaviour has been deprecated for many years. It looks to me that the bug will not be fixed, for backward compatibility reasons. If that's the case, then introducing a new range syntax is the only way to get a version of ranges in which this bug is fixed. That was another reason why OpenSCAD2 originally proposed to introduce the '..' range syntax.

Doug Moen



More information about the Discuss mailing list