All Downloads are FREE. Search and download functionalities are using the official Maven repository.

fj.data.fingertrees.Node2 Maven / Gradle / Ivy

Go to download

Functional Java is an open source library that supports closures for the Java programming language

There is a newer version: 5.0
Show newest version
package fj.data.fingertrees;

import fj.P;
import fj.P3;
import fj.data.Option;
import fj.data.vector.V2;
import fj.F;
import fj.P2;

import static fj.data.Option.none;
import static fj.data.Option.some;
import static fj.data.fingertrees.FingerTree.mkTree;

/**
 * A two-element inner tree node.
 */
public final class Node2 extends Node {
  private final V2 as;

  Node2(final Measured m, final V2 as) {
    super(m, m.sum(m.measure(as._1()), m.measure(as._2())));
    this.as = as;
  }

  @Override public  B foldRight(final F> aff, final B z) {
    return aff.f(as._1()).f(aff.f(as._2()).f(z));
  }

  @Override public  B foldLeft(final F> bff, final B z) {
    return bff.f(bff.f(z).f(as._1())).f(as._2());
  }

  public Digit toDigit() {
    return new Two(measured(), as);
  }

  P3>, A, Option>> split1(final F predicate, final V acc) {
    final Measured m = measured();
    final MakeTree mk = mkTree(m);
    if (predicate.f(m.sum(acc, m.measure().f(as._1())))) {
      return P.p(none(), as._1(), some(mk.one(as._2())));
    } else {
      return P.p(some(mk.one(as._1())), as._2(), none());
    }
  }

  @Override public P2 lookup(final F o, final int i) {
    final F m = measured().measure();
    final int s1 = o.f(m.f(as._1()));
    if (i < s1) {
      return P.p(i, as._1());
    } else {
      return P.p(i - s1, as._2());
    }
  }

  public  B match(final F, B> n2, final F, B> n3) {
    return n2.f(this);
  }

  public V2 toVector() {
    return as;
  }
}