Left-Fold in Java

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


3 thoughts on “Left-Fold in Java

  1. Pingback: Right-Fold in Java « Apocalisp

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