Associative arrays with void values

torhu no at spam.invalid
Sun Apr 12 09:07:26 PDT 2009


On 12.04.2009 17:50, Doctor J wrote:
> Sometimes you want to use an associative array just to track keys you've seen, or count distinct keys, and you don't care about the values.  The language will let you declare an array such as void[int]; but you can't actually do anything with it:
>
> void main()
> {
>      void[int] voidmap;    // This compiles
>      voidmap[1] = void;  // This doesn't
> }
>
> My question is, is this a common or useful enough special case to warrant inclusion in the language?  Or should I just go quietly and use a bool or a byte or something?
>
>
You can just use an associative array to make a set type, which has the 
operations you need.  Tango has a HashSet, but I assume you're using 
phobos.  The implementation below is very basic, but it did what I 
needed at the time.  No difference, union, or intersection operations, 
though.

struct Set(T) {
	private bool[T] data_;

	void add(T val) { data_[val] = true; }  ///
	void remove(T val) { data_.remove(val); } ///
	bool opIn_r(T val) { return (val in data_) != null; } ///
	size_t length() { return data_.length; } ///
	void rehash() { data_.rehash; } ///
	T[] toArray() { return data_.keys; } ///

	///
	static Set!(T) opCall(T[] values=null)
	{
		Set!(T) set;
		foreach (T val; values)
			set.add(val);
		return set;
	}

	///
	int opApply(int delegate(ref T) dg)
	{
		int result = 0;
		foreach (key, val; data_) {
			result = dg(key);
			if (result)
				break;
		}
		return result;
	}
}



More information about the Digitalmars-d mailing list