6.10.4 Bracket operators

If a is not an array, the notation a[i] is equivalent to a.operator[](i). Thus, the [] operator can be defined to provide this notation for a user-defined structure. Similarly, the notation a[i]=b is equivalent to a.operator[=](i,b) (except that the former always returns b). Note that there are some restrictions on how these operators can be defined:

Here is a simple example. (See Maps for data structures similar to slowMap but more flexible, more powerful, and faster.)

struct slowMap {
  string[] keys;
  real[] values;
  real operator [](string key) {
    for(int i=0; i < keys.length; ++i) {
      if(keys[i] == key) return values[i];
    }
    return -inf;
  }
  void operator [=](string key, real value) {
    assert(all(keys != key), 'duplicate key');
    keys.push(key);
    values.push(value);
  }
}

slowMap m;
m['pi']=3.14159;
m['e']=2.71828;
assert(m['pi']==3.14159);
assert(m['e']==2.71828);
assert(m['sqrt(2)'] == -inf);
write("m['pi']=", m['pi']);