com.shapesecurity.functional.data.ImmutableSet Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of shape-functional-java Show documentation
Show all versions of shape-functional-java Show documentation
Functional programming library
package com.shapesecurity.functional.data;
import com.shapesecurity.functional.F2;
import com.shapesecurity.functional.Unit;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nonnull;
@CheckReturnValue
public class ImmutableSet {
@Nonnull
private final HashTable data;
public int length() {
return this.data.length;
}
ImmutableSet(@Nonnull HashTable data) {
this.data = data;
}
public static ImmutableSet emptyUsingEquality() {
return new ImmutableSet<>(HashTable.emptyUsingEquality());
}
public static ImmutableSet emptyUsingIdentity() {
return new ImmutableSet<>(HashTable.emptyUsingIdentity());
}
@Deprecated
public static ImmutableSet empty() {
return ImmutableSet.emptyUsingEquality();
}
@Deprecated
public static ImmutableSet emptyP() {
return ImmutableSet.emptyUsingIdentity();
}
public ImmutableSet put(@Nonnull B datum) {
return new ImmutableSet<>(this.data.put(datum, Unit.unit));
}
@Nonnull
public ImmutableSet putAll(@Nonnull ImmutableList list) {
return list.foldLeft(ImmutableSet::put, this);
}
public boolean contains(@Nonnull T datum) {
return this.data.containsKey(datum);
}
public ImmutableSet remove(@Nonnull T datum) {
return new ImmutableSet<>(this.data.remove(datum));
}
public A foldAbelian(@Nonnull F2 f, @Nonnull A init) {
return this.data.foldRight((p, acc) -> f.apply(p.left, acc), init);
}
public ImmutableSet union(@Nonnull ImmutableSet other) {
return new ImmutableSet<>(this.data.merge(other.data));
}
// Does not guarantee ordering of elements in resulting list.
public ImmutableList toList() {
return this.foldAbelian((v, acc) -> acc.cons(v), ImmutableList.empty());
}
@SuppressWarnings("unchecked")
@Override
public boolean equals(Object other) {
return other instanceof ImmutableSet && this.data.length == ((ImmutableSet) other).data.length && this.data.foldLeft((memo, pair) -> memo && ((ImmutableSet) other).data.containsKey(pair.left), true);
}
}