0 or 1 index (was: new Smalltalk programmer's thoughts)

Jecel Assumpcao Jr jecel at merlintec.com
Mon May 1 13:41:31 UTC 2006


Wolfgang Helbig wrote on Mon, 1 May 2006 14:02:19 +0200 (MEST)
> And that is my point: Different challenges need different numbers for the first 
> index. When I am implementing a Gaussian algorithm to invert matrices, I'd never
> use 0 as the first index. But whenever I am computing indexes, I'd never use
> one as the first index. And this is not supported by BASIC and Smalltalk.

To be fair, I have used more than one BASIC that allowed you to set
either 0 or 1 as the base index for all arrays in a program. And the
Self dialect of Smalltalk (http://www.merlintec.com:8080/Self/) does
borrow several C conventions including 0 based arrays.

The current program I am writing in Squeak simulates hardware and 1
based arrays were a bit inconvenient, so the first thing I did was
define a ZArray class as a subclass of ArrayedCollection with

at: index
  ^ super at: index + 1

at: index put: obj
  ^ super at: index + 1 put: obj

do: block
   0 to: self size - 1 do:
         [ :index | block value: (self at: index) ]

and then all I had to do was write the rest of my application naturally
and just remember to use "ZArray new: x" instead of "Array new: x".
Inspecting ZArrays still shows the contents as having indexes starting
with 1, but other than that small confusion (which I could easily fix if
I wanted to) it works just great. There is probably a significant
performance hit but I am not worried about that here.

-- Jecel



More information about the Squeak-dev mailing list