A Terser Right Fold in Java

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>>>.

Advertisement

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