next up previous
Next: Algebraic data types Up: A slice of Pizza: Previous: Parametric polymorphism

Higher-order functions

In Java 1.1, one may use inner classes to slightly simplify the above program, by letting one move the definitions of the classes to compute orderings on integers and strings directly to the point where they are used. It can be further simplified by using the higher-order functions of Pizza.





Example 3.1 Sort in Java, with inner classes.

abstract class Ord {
  public abstract boolean leq (Object x, Object y);
}

class Sort {
  static void sort (Ord p, Object[] a) {
    for (int i = 0; i < a.length; i++) {
      for (int j = i+1; j < a.length; j++) {
        if (!p.leq(a[i],a[j])) {
          Object t=a[i]; a[i]=a[j]; a[j]=t;
  } } } }
  public static void main(String[] args) {
    Integer[] a = { new Integer(2), new Integer(1) };
    sort(new Ord {
      public boolean leq (Object x, Object y) {
        return ((Integer)x).intValue() <= ((Integer)y).intValue();
      } }, a);
    String[] b = {"data", "ditto", "dada"};
    sort(new Ord {
      public boolean leq (Object x, Object y) {
        return (((String)x).compareTo((String)y) <= 0);
      } }, b);
  }
}












Example 3.2 Sort in Pizza, with higher-order functions

class Sort {
  static <T> void sort ((T,T)->boolean p, T[] a) {
    for (int i = 0; i < a.length; i++) {
      for (int j = i+1; j < a.length; j++) {
        if (!p(a[i],a[j])) {
          T t=a[i]; a[i]=a[j]; a[j]=t;
  } } } }
  public static void main(String[] args) {
    int[] a = {2, 1};
    sort(fun(int x,int y)->boolean{return x<=y;},a);
    String[] b = {"data", "ditto", "dada"};
    sort(fun(String x,String y)->boolean{return x.compareTo(y)<=0;},b);
  }
}








Philip Wadler