Apocalisp

The end of programming as you know it

A Terser Right Fold in Java

Posted by apocalisp on May 8, 2008

By using Functional Java’s F2 and F3 interfaces, (functions of arity 2 and 3, respectively), I was able to make the right fold in Java look downright terse:


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

The curry method simply coerces an F3<A, B, C, D> by returning the equivalent F<A, F<B, F<C, D>>>.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>