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

com.jnape.palatable.lambda.functions.builtin.fn2.Iterate Maven / Gradle / Ivy

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

import com.jnape.palatable.lambda.functions.Fn1;
import com.jnape.palatable.lambda.functions.Fn2;

import java.util.Optional;
import java.util.function.Function;

import static com.jnape.palatable.lambda.adt.hlist.HList.tuple;
import static com.jnape.palatable.lambda.functions.builtin.fn2.Unfoldr.unfoldr;

/**
 * Lazily generate an infinite Iterable from the successive applications of the function first to the
 * initial seed value, then to the result, and so on; i.e., the result of iterate(x -> x + 1, 0) would
 * produce an infinite Iterable over the elements 0, 1, 2, 3, ...  and so on.
 *
 * @param  The Iterable element type
 */
public final class Iterate implements Fn2, A, Iterable> {

    private Iterate() {
    }

    @Override
    public Iterable apply(Function fn, A seed) {
        return unfoldr(a -> Optional.of(tuple(a, fn.apply(a))), seed);
    }

    public static  Iterate iterate() {
        return new Iterate<>();
    }

    public static  Fn1> iterate(Function fn) {
        return Iterate.iterate().apply(fn);
    }

    public static  Iterable iterate(Function fn, A seed) {
        return Iterate.iterate(fn).apply(seed);
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy