Apocalisp

The end of programming as you know it

Left-Fold in Java

Posted by RĂșnar on April 22, 2008

Here’s my take on a left fold in Java. Calling it is somewhat verbose, but it does the job of abstracting iteration so you don’t actually have to write another for loop on Iterable as long as you live.


  public static <A, B> A fold(F<A, F<B, A>> f, A z, Iterable<B> xs)
    { A p = z;
      for (B x : xs)
        { p = f.f(p).f(x); }
      return p; }

In case it’s not obvious, F<A, B> is an interface with one method: B f(A a).

2 Responses to “Left-Fold in Java”

  1. [...] « Noumenal Null Right-Fold in Java May 4, 2008 As an example usage of my Left-Fold in Java, here’s an implementation of a right fold that uses [...]

  2. Nice entry,

    you’ll find another variant of Left-Fold (in Java) under http://gleichmann.wordpress.com/2008/02/10/blocks-an-alternative-for-closures/

    Greetings

    Mario

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>