New set class

Frits van Bommel fvbommel at REMwOVExCAPSs.nl
Mon Feb 26 07:26:11 PST 2007


Michiel wrote:
> Stephan Diehl wrote:
> 
>> the python people have 'set' and 'frozenset'
>> (http://docs.python.org/lib/types-set.html). The main difference between
>> these two is basicly, that a 'set' can't be the key to a dict (and
>> therefore not being a member of a set. To make it short: every member of
>> a set must be immutable, or, to be more technical, must always produce
>> the same hash value. This really makes sense, if one thinks about it a
>> bit (and one wants to model sets in the more mathematical sense)
> 
> Yes, this does make sense. But my set implementation doesn't provide any
> write access to its members anyway, so you could say that everything you
> put into it automatically becomes 'frozen'.

Actually, the frozenset type doesn't allow things like add() and 
remove(). And both set and frozenset disallow changing the elements.
At least, according to the page he linked.

> Now that I think about it, I suppose it's possible to have another
> reference to an object that you are going to put into a set and change
> it through that reference. I'm not quite sure what to do with that.

You could require that any user-defined type to be put in a set has a 
.dup property/member function with postcondition ((orig !is dup) && 
(orig == dup) && (orig.opCmp(dup) == 0)), i.e. that returns a copy. And 
that it also doesn't store a reference to it anywhere else...
But then opApply would also need to .dup the value to ensure it wasn't 
modified...

This may just be more trouble than it's worth. Perhaps you should just 
say that things can get really screwed up if you change elements of a set...

> How does D handle this with its associative arrays?

I'm pretty sure it messes up if keys get altered while referenced by the 
AA, but I can't find that statement in the section of the spec dealing 
with AAs.
[later] Ah, here we go, from the comments page:
http://www.digitalmars.com/webnews/newsgroups.php?art_group=digitalmars.D&article_id=12062
Walter responds: 
http://www.digitalmars.com/webnews/newsgroups.php?art_group=digitalmars.D&article_id=12085

So yeah, don't change AA keys.

> You know, I liked C++ better in that regard. If you do an assignment or
> pass something as an argument it's automatically a copy. In Java and in
> D you have to explicitly copy something, except if it's a base type. I
> don't like exceptions like that.

IIRC there have been suggestions to add .dup to base types that just 
returns their value, for use in generic programming (i.e. templates).



More information about the Digitalmars-d mailing list