Right-Fold in Java

As an example usage of my Left-Fold in Java, here’s an implementation of a right fold that uses it. I’m using Functional Java for the F and Function classes. The List interface used here is java.util.List.


 public static <A, B> B foldr(final F<A, F<B, B>> f, B z, List<A> xs)
   {return fold
     (new F<F<B, B>, F<A, F<B, B>>>()
       {public F<A, F<B, B>> f(final F<B, B> k)
         {return new F<A, F<B, B>>()
           {public F<B, B> f(final A a)
             {return new F<B, B>()
               {public B f(B b)
                 {return k.f(f.f(a).f(b));}};}};}},
      Function.<B> id(), xs).f(z);}

If you know how to make this less verbose, I’m all ears.

Advertisement

One thought on “Right-Fold in Java

  1. Pingback: FoldLeft, FoldRight « Marco Faustinelli's Blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s