All Downloads are FREE. Search and download functionalities are using the official Maven repository.

no.finn.lambdacompanion.Functions Maven / Gradle / Ivy

There is a newer version: 0.27
Show newest version
package no.finn.lambdacompanion;

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

public final class Functions {

    private Functions() {
    }

    /**
     * @param  a
     * @param  b
     * @param accumulator accumulator
     * @param b b
     * @param list list
     * @return b
     * Head recursive fold. Fold the list by combining the first element with the results of combining the rest
     * 

* Example: *

     * {@code
     *    :                                    f
     *   / \       foldRight f z ->           / \
     *  1   :                                1   f
     *     / \                                  / \
     *    2  []                                2   z
     * }
     * 
*/ public static B foldRight(final BiFunction accumulator, final B b, final List
list) { return list.isEmpty() ? b : accumulator.apply(head(list), foldRight(accumulator, b, tail(list))); } /** * @param a * @param b * @param accumulator accumulator * @param b b * @param list list * @return b * Tail recursive fold. Fold the list by recursively combining the results of combining all but the last element with the last one *

* Example: *

     * {@code
     *    :                                    f
     *   / \       foldLeft f z ->            / \
     *  1   :                                f   2
     *     / \                              / \
     *    2  []                            z   1
     * }
     * 
*/ public static B foldLeft(final BiFunction accumulator, final B b, final List
list) { return list.isEmpty() ? b : foldLeft(accumulator, accumulator.apply(head(list), b), tail(list)); } /** * @param a * @param list list * @return first element of the given list. * @throws IndexOutOfBoundsException if the list is empty */ public static A head(final List list) { return list.get(0); } /** * @param a * @param list list * @return all but the first elements of the given list * @throws IndexOutOfBoundsException if the list is empty */ public static List tail(final List list) { return list.subList(1, list.size()); } }