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

com.jnape.palatable.lambda.functions.builtin.fn3.ScanLeft Maven / Gradle / Ivy

There is a newer version: 5.5.0
Show newest version
package com.jnape.palatable.lambda.functions.builtin.fn3;

import com.jnape.palatable.lambda.functions.Fn1;
import com.jnape.palatable.lambda.functions.Fn2;
import com.jnape.palatable.lambda.functions.Fn3;
import com.jnape.palatable.lambda.iterators.ScanningIterator;

import java.util.function.BiFunction;

/**
 * Given an Iterable of As, a starting value B, and a {@link
 * BiFunction}<B, A, B>, iteratively accumulate over the Iterable, collecting each function
 * application result, finally returning an Iterable of all the results. Note that, as the name implies,
 * this function accumulates from left to right, such that scanLeft(f, 0, asList(1,2,3,4,5)) is evaluated
 * as 0, f(0, 1), f(f(0, 1), 2), f(f(f(0, 1), 2), 3), f(f(f(f(0, 1), 2), 3), 4), f(f(f(f(f(0, 1), 2), 3), 4), 5).
 *
 * @param  The Iterable element type
 * @param  The accumulation type
 * @see FoldLeft
 */
public final class ScanLeft implements Fn3, B, Iterable, Iterable> {

    private static final ScanLeft INSTANCE = new ScanLeft();

    private ScanLeft() {
    }

    @Override
    public Iterable apply(BiFunction fn, B b, Iterable as) {
        return () -> new ScanningIterator<>(fn, b, as.iterator());
    }

    @SuppressWarnings("unchecked")
    public static  ScanLeft scanLeft() {
        return INSTANCE;
    }

    public static  Fn2, Iterable> scanLeft(BiFunction fn) {
        return ScanLeft.scanLeft().apply(fn);
    }

    public static  Fn1, Iterable> scanLeft(BiFunction fn, B b) {
        return ScanLeft.scanLeft(fn).apply(b);
    }

    public static  Iterable scanLeft(BiFunction fn, B b, Iterable as) {
        return ScanLeft.scanLeft(fn, b).apply(as);
    }
}