Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing Set<T>

Tags:

abstract

haxe

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?

like image 938
Michael Avatar asked Sep 28 '18 16:09

Michael


People also ask

What is implementation of set?

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.

How do you implement a set in Java?

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.

Which data structure is used for implementing set?

7.2–7.3). 3 The three most common data structures used to implement sets: linked lists, characteristic vectors, and hash tables.


1 Answers

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

like image 170
back2dos Avatar answered Sep 29 '22 03:09

back2dos