Can one define own indexing function/mapping to be used for an Array
- To: mathgroup at smc.vnet.net
- Subject: [mg113338] Can one define own indexing function/mapping to be used for an Array
- From: "Nasser M. Abbasi" <nma at 12000.org>
- Date: Sun, 24 Oct 2010 06:05:29 -0400 (EDT)
- Reply-to: nma at 12000.org
I am trying to implement something where it is more natural to use an
index that starts at 0 instead of the default 1 for vectors and matrices
as since this will match the problem I am looking at.
If I write
u={0,1,2}
u[[0]]
This will return the Head of u. So have to write u[[1]] to get the first
entry. I'd like to write u[[0]] to get the first entry.
I thought about using Array:
In[8]:= u = Array[U[#1] & , 4, 0]
Out[8]= {U[0], U[1], U[2], U[3]}
But this does not do much, I still have to write u[[1]] to access U[0]
I could write my own function to implement a 'get' and 'set' operations
as in:
In[4]:= get[u_, i_] := u[[i + 1]]
In[5]:= get[u, 0]
Out[5]= U[0]
So, everywhere in the code, where I would have liked to write u[[i]], I
will replace that by get[u,i], and now my i's will match the textbook
i's since those are implemented using 0-index arrays.
In an OO setting, I could have defined my own "[[ ]]" function on object
of type Array, then I can write more u[[i]], where now u's own function
"[[ ]]" will be used.
Other languages also allow one to define an array with different
starting index than the default.
Is there a way to do something like this for Array at least. For general
Lists, I think that might not be possible? It will break everything I
would imagine.
I am looking at this report:
http://library.wolfram.com/conferences/devconf99/lichtblau/
"Data Structures and Efficient Algorithms in Mathematica",
But thought to also ask here, to see if there might be a simple trick to
do this for Array, by unprotecting it, and changing something? and then
protecting the definition again, before I try to implement a data struct
with the help of the above article to do what I want.
thanks
--Nasser