[plt-scheme] Functional Abstraction in Java

From: David Van Horn (dvanhorn at ccs.neu.edu)
Date: Wed Jul 1 14:10:23 EDT 2009

Andrei Estioco wrote:
> Hello. My apologies if I am asking this in the wrong mailing list (this 
> being a Java question). 

This is *the* list for this sort of question.

You can think of functions A -> B as objects satisfying the interface B 
apply(A).  So all of your favorite functional idioms can be expressed in 
Java, just with considerable notational overhead.  It's fun to try -- so 
don't just take my word for it.

Here is a simple program that shows how to develop filter (which 
abstracts the predicate to apply):


Here is a higher-order example, the derivative function:

class Calculus {

   interface IFun1<X,Y> { Y apply(X x); }

   IFun1<IFun1<Double,Double>,IFun1<Double,Double>> deriv =
     new IFun1<IFun1<Double,Double>,IFun1<Double,Double>>() {
       double d = 0.001;
       public IFun1<Double,Double> apply(final IFun1<Double,Double> f) {
         return new IFun1<Double,Double>() {
           public Double apply(Double x) {
             return (f.apply(x + d) - f.apply(x - d)) / (d * 2);

   IFun1<Double,Double> sin = new IFun1<Double,Double>() {
     public Double apply(Double x) { return Math.sin(x); }

   IFun1<Double,Double> cos = deriv.apply(sin);

Finally, you can find more of this in the Little Java book (and in the 
forthcoming HtDC book).


Posted on the users mailing list.