diff --git a/src/main/java/com/samskivert/util/Folds.java b/src/main/java/com/samskivert/util/Folds.java index 156331fb..668bcb5a 100644 --- a/src/main/java/com/samskivert/util/Folds.java +++ b/src/main/java/com/samskivert/util/Folds.java @@ -22,6 +22,7 @@ package com.samskivert.util; import java.math.BigInteger; import java.util.Collection; +import java.util.Iterator; import java.util.Map; /** @@ -29,6 +30,42 @@ import java.util.Map; */ public class Folds { + /** Used with {@link #foldLeft}. */ + public interface F + { + /** Folds the supplied element into the result. */ + B apply (B zero, A elem); + } + + /** For reductions and same-typed folds. */ + public interface R extends F {} + + /** + * Left folds the supplied function over the supplied values using the supplied starting value. + */ + public static B foldLeft (F func, B zero, Iterable values) + { + for (A value : values) { + zero = func.apply(zero, value); + } + return zero; + } + + /** + * Reduces the supplied values using the supplied function with a left fold. + * + * @exception NoSuchElementException thrown if values does not contain at least one element. + */ + public static A reduceLeft (F func, Iterable values) + { + Iterator iter = values.iterator(); + A zero = iter.next(); + while (iter.hasNext()) { + zero = func.apply(zero, iter.next()); + } + return zero; + } + /** * Sums the supplied collection of numbers to an int with a left to right fold. */