Apocalisp

The end of programming as you know it

Right-Fold in Java

Posted by RĂșnar on May 4, 2008

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.

Leave a Reply

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