Wrong calculation of array indices

BlitzMax Forums/BlitzMax Programming/Wrong calculation of array indices

Mik1e(Posted 2010) [#1]
Hi guys,

I've met with strange (counter-intuitive) behavior of arrays.

Here is the code:
SuperStrict
Local a%[] = New Int[10]
For Local i% = 0 To 9
	a[i] = i
Next
Local b%[] = a[1..2]

DebugStop


Expected behavior: b should contain TWO elements of array a (namely, 1 and 2), but it contains only ONE element -- 1.

This bug is easy enough to fix, but in the last version it is still present :(


plash(Posted 2010) [#2]
I believe that is how slices were intended to behave.


Floyd(Posted 2010) [#3]
And it is similar to the way array indices are defined. The ten-element array goes from a[0] to a[9].

Slices are described in the Language Reference. As stated, the number of elements in a[First..Last] is Last-First.

I think BlitzMax array slicing was designed by mixing various aspects of slices in Perl and Python.


Mik1e(Posted 2010) [#4]
And it is similar to the way array indices are defined. The ten-element array goes from a[0] to a[9].


You are right -- arrays indexing stars from zero, so in my example array a elements are indexed from 0 to 9. So, if I write b%[] = a[1..10], it should rise error (if expression [M..N] means "Take elements with indexes from M to N"), but it will not. You may say that slices are 1-based, but in this case expression b[] = a[0..9] should rise error, and it does not, too.

As I understand, now slicing algorithm simply takes (N-M) elements starting from element with number M. This is not correct, since expression b%[] = a[M..M] will generate Null array b (while I want just to take the element with number M). So, if I want to get the slice of N elements starting from element M, I have to write b[] = a[M..M+N+1]. This is definitely not correct. Look at slicing at Matlab -- there a = b(1:10) will create the vector a with TEN elements.

Resume: slicing algorithm should be corrected to take (N-M+1) elements, and then it will be correct.


Floyd(Posted 2010) [#5]
You will NEVER win this argument.

The current behavior is by design. Even if we agree the design is wrong it can't be changed now. That would break all previous code which uses slices.

Slicing works exactly as just described. a[M..N] has N-M elements, starting with a[M]. Thus a[M..M] has zero elements, a[M..M+1] has one element. You may not like this notation, but that's the way it is.


Mik1e(Posted 2010) [#6]
The current behavior is by design. Even if we agree the design is wrong it can't be changed now. That would break all previous code which uses slices.


I understand this. Anyway, I'd prefer to see the same syntax as in Matlab and other math packages, when I need not make calculations in mind, but simply get what I need.