associative arrays

bearophile bearophileHUGS at lycos.com
Sat Jan 7 18:54:07 PST 2012


RenatoL:

> Yes, Jonathan, you're right.
> the question arose precisely from a typo... i had to remove an
> item with key "length"... i wrote "lengt" and the item never went
> away... i knew that "lengt" was not in my key list... This kind of
> mistake is quite tricky, may be using and IDE could help.

This an example that shows that silent failures are sources of bugs...
So this time I don't agree with Jonathan Davis.

Python Zen contains:
Errors should never pass silently.

And Python associative arrays show it:

>>> d = {1:2, 3:4}
>>> del d[5]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 5


The successive rule of the Python Zen says:
Unless explicitly silenced.

Python sets show this at work, they have a 'remove' method that throws if the item is missing, plus a 'discard' method that acts more like D associative arrays, in a sense it's a way to silence explicitly the error:

>>> s = set([1, 2])
>>> s.discard(1)
>>> s
set([2])
>>> s = set([1, 2])
>>> s.discard(3)
>>> s
set([1, 2])
>>> s.remove(3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 3

Maybe D associative arrays too should have both kinds of deleting methods :-)

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list