
fj.data.fingertrees.Single Maven / Gradle / Ivy
package fj.data.fingertrees;
import fj.F;
import fj.P;
import fj.P2;
import fj.P3;
import fj.Show;
import fj.data.Stream;
import static fj.P.p;
import static fj.Show.anyShow;
/**
* A tree with a single element.
*/
public final class Single extends FingerTree {
private final A a;
private final V v;
Single(final Measured m, final A a) {
super(m);
this.a = a;
v = m.measure(a);
}
@Override public B foldRight(final F> aff, final B z) {
return aff.f(a).f(z);
}
@Override public A reduceRight(final F> aff) {
return a;
}
@Override public B foldLeft(final F> bff, final B z) {
return bff.f(z).f(a);
}
@Override public A reduceLeft(final F> aff) {
return a;
}
@Override public FingerTree map(final F abf, final Measured m) {
return new Single<>(m, abf.f(a));
}
/**
* Returns the annotation of this tree's single element.
*
* @return the annotation of this tree's single element.
*/
public V measure() {
return v;
}
/**
* Pattern matching on the structure of this tree. Matches the singleton tree.
*/
@Override public B match(final F, B> empty, final F, B> single,
final F, B> deep) {
return single.f(this);
}
@Override public FingerTree cons(final A b) {
final MakeTree mk = mkTree(measured());
return mk.deep(mk.one(b), new Empty<>(measured().nodeMeasured()), mk.one(a));
}
@Override public FingerTree snoc(final A b) {
final MakeTree mk = mkTree(measured());
return mk.deep(mk.one(a), new Empty<>(measured().nodeMeasured()), mk.one(b));
}
@Override public A head() { return a; }
@Override public A last() { return a; }
@Override public FingerTree tail() { return new Empty<>(measured()); }
@Override public FingerTree init() { return new Empty<>(measured()); }
@Override public FingerTree append(final FingerTree t) {
return t.cons(a);
}
@Override P3, A, FingerTree> split1(final F predicate, final V acc) {
final Empty empty = new Empty<>(measured());
return p(empty, a, empty);
}
@Override public P2 lookup(final F o, final int i) { return p(i, a); }
@Override
public int length() {
return 1;
}
/**
* Returns the single element of this tree.
*
* @return the single element of this tree.
*/
public A value() {
return a;
}
public String toString() {
return Show.fingerTreeShow(Show.anyShow(), Show.anyShow()).showS(this);
}
public Stream toStream() {
return Stream.single(a);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy