aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/org/zwobble/couscous/util/Fold.java
blob: e86454eac726dd7f582280b837755c2b17341d33 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package org.zwobble.couscous.util;

import com.google.common.collect.Lists;

import java.util.List;
import java.util.function.BiFunction;

public class Fold {
    public static <T, V> V foldLeft(Iterable<T> iterable, V initialValue, BiFunction<V, T, V> function) {
        V value = initialValue;
        for (T element : iterable) {
            value = function.apply(value, element);
        }
        return value;
    }

    public static <T, V> V foldRight(List<T> iterable, V initialValue, BiFunction<V, T, V> function) {
        return foldLeft(Lists.reverse(iterable), initialValue, function);
    }
}