I'm trying to wrap my head around abstract
by implementing a Set
data-type, like so:
abstract Set<T>(Map<T, Bool>) {
public inline function new() {
this = new Map<T, Bool>();
}
public inline function has(item:T):Bool {
return this.exists(item);
}
public inline function add(item:T):Set<T> {
this.set(item, true);
return null;
}
public inline function remove(item:T):Set<T> {
this.remove(item);
return null;
}
public inline function iterator():Iterator<T> {
return this.keys();
}
}
The compiler doesn't like this, though. It tells me Set.hx:8: characters 11-29 : Abstract Map has no @:to function that accepts IMap<util.Set.T, Bool>
I don't really understand this at all, since if I change the constructor to
public inline function new(val:Map<T, Bool>) {
this = val;
}
and then instantiate with var set = new Set(new Map());
, it works.
That's pretty gross, though. I'd like the ability to instantiate Sets without exposing the underlying implementation. Ultimately, I'd prefer a constructor with the signature new(?initial:Iterable<T>)
. Is this possible? Am I misunderstanding something?
There are three general-purpose Set implementations — HashSet , TreeSet , and LinkedHashSet . Which of these three to use is generally straightforward. HashSet is much faster than TreeSet (constant-time versus log-time for most operations) but offers no ordering guarantees.
A HashSet implements Set interface which does not allow duplicate values. A HashSet is not synchronized and is not thread-safe. When we can add any duplicate element to a HashSet, the add() method returns false and does not allow to add a duplicate element to HashSet.
7.2–7.3). 3 The three most common data structures used to implement sets: linked lists, characteristic vectors, and hash tables.
The problem is that currently it's impossible to instantiate Map
without they key type being known (and since Set.T
is a free type parameter, this doesn't work). However since the constructor is inline
, T
may well be known at the call site. The problem is that the compiler still tries to generate Set.new
. You can avoid this by prefixing it with @:extern
. Working example: https://try.haxe.org/#1D06C
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With