Hash Set Data Structure, only Keys

Question 1: Looking to find a data structure in Haxe (or create one) that is a somewhat simplified ObjectMap (without the actual mapping part)

var set = new Set<T>();

set.add(t:T)                  // adds element to set IFF element is not already in set
set.getElements():Array<T>    // returns all the elements in the set
set.clear()                   // clears all the elements in the set

At the moment I’ve been using a Map<T, Bool> to get similar functionality

For adding elements, I’m using map.set(t, true)
For looping through elements, I’m running for(key in map.keys())
For clearing the structure, I’m using map = new Map<T, Bool>()

Is there a better method? Does a class like the one I’m looking for already exist?

Question 2: is there a class like the one I’m looking for that can be composed in a templated superclass? At the moment, Map cannot be used as such, because the first argument cannot be a template variable.


class System<T> {
     var set:Set<T>;
     public function new() {
          set = new Set<T>();

Thanks for any help in advance :slight_smile:

I’ve looked this up before, and the answers I found said to use a Map instead. Not exactly ideal, I agree.

Then for Question 2): do you know if something like this is possible with Map? The Haxe compiler doesn’t let me do the following:

class System<T> {
     var map:Map<T, Bool>;
     public function new() {
          map = new Map<T, Bool>();

Basically, is there an easy way to create a hash function for pointers in haxe? Is it possible to create a

function hash(t:T):String

That creates a unique string for an object pointer* ?
* that is computed the same way even if the object’s data changes

Not that I know of, but if you can get the pointer yourself, you can use an instance of Map<Int, T>. You’ll need platform-specific code for this, and you have a very limited number of targets:

function hash(t:T):Int {
    #if cpp
        return untyped __cpp__("&t");
    #elseif csharp
        return untyped __csharp__("&t");
    #elseif python
        //Only works in CPython.
        return untyped __python__("id(t)");
    #elseif php
        return untyped __php__("&$t");
        throw "Can't get memory addresses on this platform!";

Note: I haven’t tested this code.

This might be possible with @:generic class System<T>

Huh. For some reason I thought @:generic had been dropped. (Maybe what really happened is I had trouble getting it to work, so I stopped using it. I don’t know; it was a while ago.)

Anyway, it’s still in the manual, so you might as well give it a shot.

Looks like ObjectMap has constraint for key - key : { }. It started to work, if you add the same constraint on System - System<T: {}>.

Example of abstract object set: https://try.haxe.org/#29993

Thank you restorer! That looks like a great solution to what I was looking for! :slight_smile: