foldLeft implementation

foldeLeft (folding in general) is one of the most powerful functional construct. Clean, elegant and generic.

Almost all functional operations can be built on top of the fold functions. So you need to have one. Once you have foldLeft you got a bunch of “operation” in addition (see later).

A few example how foldLeft can be used:

I had a continuous need of implementing some min and max on collection and I wanted to add my functional FIterable . So I did.

 1  public interface F2<X, Y, Z> {
 2    public Z f(X p1, Y p2);
 3
 4    public static interface Simple<T> extends F2<T, T, T> {
 5    }
 6
 7    public static interface Collector<V, S> extends F2<V, S, V> {
 8    }
 9  }
10
11//....
12
13
14  public <C> C foldLeft(C init, F2<C, T, C> reducer) {
15    for (T i : this.iterable) {
16      init = reducer.f(init, i);
17    }
18    return init;
19  }
20
21//...
22
23  @Test
24  public void foldLeft() throws Exception {
25    Integer res = FIterable(IList(1, 2, 3, 4)).foldLeft(0, new F2.Collector<Integer, Integer>() {
26      @Override
27      public Integer f(Integer p1, Integer p2) {
28        return p1 + p2;
29      }
30    });
31    assertEquals(10, res.intValue());
32
33    String longestString = FIterable(IList("aaaaa", "a", "qqqqqqqqqqq", "bb")).foldLeft("", new F2.Simple<String>() {
34      @Override
35      public String f(String p1, String p2) {
36        return p1.length() > p2.length() ? p1 : p2;
37      }
38    });
39    assertEquals("qqqqqqqqqqq", longestString);
40  }
Jul 14, 2014
comments powered by Disqus

Links

Cool

RSS