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

fj.Ord 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;

import fj.data.Array;
import fj.data.Either;
import fj.data.List;
import fj.data.Natural;
import fj.data.NonEmptyList;
import fj.data.Option;
import fj.data.Set;
import fj.data.Stream;
import fj.data.Validation;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Comparator;

import static fj.Function.apply;
import static fj.Function.compose;
import static fj.Function.curry;
import static fj.Semigroup.semigroup;

/**
 * Tests for ordering between two objects.
 *
 * @version %build.number%
 */
public final class Ord {
  private final F> f;

  private Ord(final F> f) {
    this.f = f;
    this.max = a1 -> apply((a2, o) -> o == Ordering.GT ? a1 : a2, f.f(a1));
    this.min = a1 -> apply((a2, o) -> o == Ordering.LT ? a1 : a2, f.f(a1));
  }

  /**
   * First-class ordering.
   *
   * @return A function that returns an ordering for its arguments.
   */
  public F> compare() {
    return f;
  }

  /**
   * Returns an ordering for the given arguments.
   *
   * @param a1 An instance to compare for ordering to another.
   * @param a2 An instance to compare for ordering to another.
   * @return An ordering for the given arguments.
   */
  public Ordering compare(final A a1, final A a2) {
    return f.f(a1).f(a2);
  }

  /**
   * Returns true if the given arguments are equal, false otherwise.
   *
   * @param a1 An instance to compare for equality to another.
   * @param a2 An instance to compare for equality to another.
   * @return true if the given arguments are equal, false otherwise.
   */
  public boolean eq(final A a1, final A a2) {
    return compare(a1, a2) == Ordering.EQ;
  }

  /**
   * Returns an Equal for this order.
   *
   * @return An Equal for this order.
   */
  public Equal equal() {
    return Equal.equal(a -> compose(o -> o == Ordering.EQ, f.f(a)));
  }

  /**
   * Maps the given function across this ord as a contra-variant functor.
   *
   * @param f The function to map.
   * @return A new ord.
   */
  public  Ord contramap(final F f) {
    return ord(F1Functions.o(F1Functions.o(F1Functions.andThen(f), this.f), f));
  }

  /**
   * Returns true if the first given argument is less than the second given argument,
   * false otherwise.
   *
   * @param a1 An instance to compare for ordering to another.
   * @param a2 An instance to compare for ordering to another.
   * @return true if the first given argument is less than the second given argument,
   *         false otherwise.
   */
  public boolean isLessThan(final A a1, final A a2) {
    return compare(a1, a2) == Ordering.LT;
  }

    /**
     * Returns true if the first given argument is less than or equal to the second given argument,
     * false otherwise.
     *
     * @param a1 An instance to compare for ordering to another.
     * @param a2 An instance to compare for ordering to another.
     * @return true if the first given argument is less than or equal to the second given argument,
     *         false otherwise.
     */
    public boolean isLessThanOrEqualTo(final A a1, final A a2) {
        return compare(a1, a2) != Ordering.GT;
    }

  /**
   * Returns true if the first given argument is greater than the second given
   * argument, false otherwise.
   *
   * @param a1 An instance to compare for ordering to another.
   * @param a2 An instance to compare for ordering to another.
   * @return true if the first given argument is greater than the second given
   *         argument, false otherwise.
   */
  public boolean isGreaterThan(final A a1, final A a2) {
    return compare(a1, a2) == Ordering.GT;
  }

  /**
   * Returns a function that returns true if its argument is less than the argument to this method.
   *
   * @param a A value to compare against.
   * @return A function that returns true if its argument is less than the argument to this method.
   */
  public F isLessThan(final A a) {
    return compose(o -> o != Ordering.LT, f.f(a));
  }

  /**
   * Returns a function that returns true if its argument is greater than than the argument to this method.
   *
   * @param a A value to compare against.
   * @return A function that returns true if its argument is greater than the argument to this method.
   */
  public F isGreaterThan(final A a) {
    return compose(o -> o != Ordering.GT, f.f(a));
  }

  /**
   * Returns the greater of its two arguments.
   *
   * @param a1 A value to compare with another.
   * @param a2 A value to compare with another.
   * @return The greater of the two values.
   */
  public A max(final A a1, final A a2) {
    return isGreaterThan(a1, a2) ? a1 : a2;
  }


  /**
   * Returns the lesser of its two arguments.
   *
   * @param a1 A value to compare with another.
   * @param a2 A value to compare with another.
   * @return The lesser of the two values.
   */
  public A min(final A a1, final A a2) {
    return isLessThan(a1, a2) ? a1 : a2;
  }

  /**
   * A function that returns the greater of its two arguments.
   */
  public final F> max;

  /**
   * A function that returns the lesser of its two arguments.
   */
  public final F> min;

  public final Semigroup minSemigroup() {
      return semigroup(min);
  }

  public final Semigroup maxSemigroup() {
      return semigroup(max);
  }

  public final Ord reverse() { return ord(Function.flip(f)); }

  /**
   * Returns an order instance that uses the given equality test and ordering function.
   *
   * @param f The order function.
   * @return An order instance.
   */
  public static  Ord ord(final F> f) {
    return new Ord<>(f);
  }

  /**
   * An order instance for the boolean type.
   */
  public static final Ord booleanOrd = comparableOrd();

  /**
   * An order instance for the byte type.
   */
  public static final Ord byteOrd = comparableOrd();

  /**
   * An order instance for the char type.
   */
  public static final Ord charOrd = comparableOrd();

  /**
   * An order instance for the double type.
   */
  public static final Ord doubleOrd = comparableOrd();

  /**
   * An order instance for the float type.
   */
  public static final Ord floatOrd = comparableOrd();

  /**
   * An order instance for the int type.
   */
  public static final Ord intOrd = comparableOrd();

  /**
   * An order instance for the BigInteger type.
   */
  public static final Ord bigintOrd = comparableOrd();

  /**
   * An order instance for the BigDecimal type.
   */
  public static final Ord bigdecimalOrd = comparableOrd();

  /**
   * An order instance for the long type.
   */
  public static final Ord longOrd = comparableOrd();

  /**
   * An order instance for the short type.
   */
  public static final Ord shortOrd = comparableOrd();

  /**
   * An order instance for the {@link Ordering} type.
   */
  public static final Ord orderingOrd = Ord.ord(curry((o1, o2) -> o1 == o2 ?
         Ordering.EQ :
         o1 == Ordering.LT ?
         Ordering.LT :
         o2 == Ordering.LT ?
         Ordering.GT :
         o1 == Ordering.EQ ?
         Ordering.LT :
         Ordering.GT));

  /**
   * An order instance for the {@link String} type.
   */
  public static final Ord stringOrd = comparableOrd();

  /**
   * An order instance for the {@link StringBuffer} type.
   */
  public static final Ord stringBufferOrd = stringOrd.contramap(StringBuffer::toString);

  /**
   * An order instance for the {@link StringBuffer} type.
   */
  public static final Ord stringBuilderOrd = stringOrd.contramap(StringBuilder::toString);

  /**
   * An order instance for the {@link Option} type.
   *
   * @param oa Order across the element of the option.
   * @return An order instance for the {@link Option} type.
   */
  public static  Ord> optionOrd(final Ord oa) {
    return ord(o1 -> o2 -> o1.isNone() ?
            o2.isNone() ?
                    Ordering.EQ :
                    Ordering.LT :
            o2.isNone() ?
                    Ordering.GT :
                    oa.f.f(o1.some()).f(o2.some()));
  }

  /**
   * An order instance for the {@link Either} type.
   *
   * @param oa Order across the left side of {@link Either}.
   * @param ob Order across the right side of {@link Either}.
   * @return An order instance for the {@link Either} type.
   */
  public static  Ord> eitherOrd(final Ord oa, final Ord ob) {
    return ord(e1 -> e2 -> e1.isLeft() ?
            e2.isLeft() ?
                    oa.f.f(e1.left().value()).f(e2.left().value()) :
                    Ordering.LT :
            e2.isLeft() ?
                    Ordering.GT :
                    ob.f.f(e1.right().value()).f(e2.right().value()));
  }

  /**
   * An order instance for the {@link Validation} type.
   *
   * @param oa Order across the failing side of {@link Validation}.
   * @param ob Order across the succeeding side of {@link Validation}.
   * @return An order instance for the {@link Validation} type.
   */
  public static  Ord> validationOrd(final Ord oa, final Ord ob) {
    return eitherOrd(oa, ob).contramap(Validation.either());
  }

  /**
   * An order instance for the {@link List} type.
   *
   * @param oa Order across the elements of the list.
   * @return An order instance for the {@link List} type.
   */
  public static  Ord> listOrd(final Ord oa) {
    return ord(l1 -> l2 -> {
      List x1 = l1;
      List x2 = l2;

      while (x1.isNotEmpty() && x2.isNotEmpty()) {
        final Ordering o = oa.compare(x1.head(), x2.head());
        if (o == Ordering.LT || o == Ordering.GT) {
          return o;
        }
        x1 = x1.tail();
        x2 = x2.tail();
      }

      if (x1.isEmpty() && x2.isEmpty()) {
        return Ordering.EQ;
      } else if (x1.isEmpty()) {
        return Ordering.LT;
      } else {
        return Ordering.GT;
      }
    });
  }

  /**
   * An order instance for the {@link NonEmptyList} type.
   *
   * @param oa Order across the elements of the non-empty list.
   * @return An order instance for the {@link NonEmptyList} type.
   */
  public static  Ord> nonEmptyListOrd(final Ord oa) {
    return listOrd(oa).contramap(NonEmptyList.toList_());
  }

  /**
   * An order instance for the {@link Stream} type.
   *
   * @param oa Order across the elements of the stream.
   * @return An order instance for the {@link Stream} type.
   */
  public static  Ord> streamOrd(final Ord oa) {
    return ord(s1 -> s2 -> {
        if (s1.isEmpty())
            return s2.isEmpty() ? Ordering.EQ : Ordering.LT;
        else if (s2.isEmpty())
            return s1.isEmpty() ? Ordering.EQ : Ordering.GT;
        else {
            final Ordering c = oa.compare(s1.head(), s2.head());
            return c == Ordering.EQ ? streamOrd(oa).f.f(s1.tail()._1()).f(s2.tail()._1()) : c;
        }
    });
  }

  /**
   * An order instance for the {@link Array} type.
   *
   * @param oa Order across the elements of the array.
   * @return An order instance for the {@link Array} type.
   */
  public static  Ord> arrayOrd(final Ord oa) {
    return ord(a1 -> a2 -> {
        int i = 0;
        //noinspection ForLoopWithMissingComponent
        for (; i < a1.length() && i < a2.length(); i++) {
            final Ordering c = oa.compare(a1.get(i), a2.get(i));
            if (c == Ordering.GT || c == Ordering.LT)
                return c;
        }
        return i == a1.length() ?
                i == a2.length() ?
                        Ordering.EQ :
                        Ordering.LT :
                i == a1.length() ?
                        Ordering.EQ :
                        Ordering.GT;
    });
  }

  /**
   * An order instance for the {@link Set} type.
   *
   * @param oa Order across the elements of the set.
   * @return An order instance for the {@link Set} type.
   */
  public static  Ord> setOrd(final Ord oa) {
    return streamOrd(oa).contramap(Set::toStream);
  }

  /**
   * An order instance for the {@link Unit} type.
   */
  public static final Ord unitOrd = ord(curry((Unit u1, Unit u2) -> Ordering.EQ));

  /**
   * An order instance for a product-1.
   *
   * @param oa Order across the produced type.
   * @return An order instance for a product-1.
   */
  public static  Ord> p1Ord(final Ord oa) {
    return oa.contramap(P1.__1());
  }


  /**
   * An order instance for a product-2, with the first factor considered most significant.
   *
   * @param oa An order instance for the first factor.
   * @param ob An order instance for the second factor.
   * @return An order instance for a product-2, with the first factor considered most significant.
   */
  public static  Ord> p2Ord(final Ord oa, final Ord ob) {
    return ord(curry((P2 a, P2 b) -> oa.eq(a._1(), b._1()) ? ob.compare(a._2(), b._2()) : oa.compare(a._1(), b._1())));
  }

    public static  Ord> p2Ord1(Ord oa) {
        return ord(p1 -> p2 -> oa.compare(p1._1(), p2._1()));
    }

    public static  Ord> p2Ord2(Ord ob) {
        return ord(p1 -> p2 -> ob.compare(p1._2(), p2._2()));
    }

  /**
   * An order instance for a product-3, with the first factor considered most significant.
   *
   * @param oa An order instance for the first factor.
   * @param ob An order instance for the second factor.
   * @param oc An order instance for the third factor.
   * @return An order instance for a product-3, with the first factor considered most significant.
   */
  public static  Ord> p3Ord(final Ord oa, final Ord ob, final Ord oc) {
    return ord(curry((P3 a, P3 b) -> oa.eq(a._1(), b._1()) ?
           p2Ord(ob, oc).compare(P.p(a._2(), a._3()), P.p(b._2(), b._3()))
                                 : oa.compare(a._1(), b._1())));
  }

  /**
   * An order instance for the Natural type.
   */
  public static final Ord naturalOrd = bigintOrd.contramap(Natural.bigIntegerValue);


  /**
   * An order instance for the Comparable interface.
   *
   * @return An order instance for the Comparable interface.
   */
  public static > Ord comparableOrd() {

    return ord(a1 -> a2 -> Ordering.fromInt(a1.compareTo(a2)));
  }

  /**
   * An order instance that uses {@link Object#hashCode()} for computing the order and equality,
   * thus objects returning the same hashCode are considered to be equals (check {@link #hashEqualsOrd()}
   * for an additional check on {@link Object#equals(Object)}).
   *
   * @return An order instance that is based on {@link Object#hashCode()}.
   * @see #hashEqualsOrd()
   */
  public static  Ord hashOrd() {
    return ord(a -> {
      int aHash = a.hashCode();
      return a2 -> Ordering.fromInt(Integer.valueOf(aHash).compareTo(a2.hashCode()));
    });
  }

  /**
   * An order instance that uses {@link Object#hashCode()} and {@link Object#equals} for computing
   * the order and equality. First the hashCode is compared, if this is equal, objects are compared
   * using {@link Object#equals}.
   *
   * @return An order instance that is based on {@link Object#hashCode()} and {@link Object#equals}.
   */
  public static  Ord hashEqualsOrd() {
    return ord(a -> {
      int aHash = a.hashCode();
      return a2 -> {
        final int a2Hash = a2.hashCode();
        return aHash < a2Hash ? Ordering.LT : aHash == a2Hash && a.equals(a2) ? Ordering.EQ : Ordering.GT;
      };
    });
  }

  class OrdComparator implements Comparator {
	@Override
    public final int compare(A o1, A o2) {
	    return Ord.this.compare(o1, o2).toInt();
    }
  }

  public Comparator toComparator() {
	  return new OrdComparator();
  }
}