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

com.jnape.palatable.lambda.functions.builtin.fn3.Times 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 static com.jnape.palatable.lambda.functions.builtin.fn2.Replicate.replicate;
import static com.jnape.palatable.lambda.functions.builtin.fn3.FoldLeft.foldLeft;

/**
 * Given some number of times n to invoke a function A -> A, and given an input
 * A, iteratively apply the function to the input, and then to the result of the invocation, a total of
 * n times, returning the result.
 * 

* Example: * * times(3, x -> x + 1, 0); // 3 * * @param the input and output type */ public final class Times implements Fn3, A, A> { private static final Times INSTANCE = new Times<>(); private Times() { } @Override public A checkedApply(Integer n, Fn1 fn, A a) { if (n < 0) throw new IllegalStateException("n must not be less than 0"); return foldLeft((acc, f) -> f.apply(acc), a, replicate(n, fn)); } @SuppressWarnings("unchecked") public static Times times() { return (Times) INSTANCE; } public static Fn2, A, A> times(Integer n) { return Times.times().apply(n); } public static Fn1 times(Integer n, Fn1 fn) { return Times.times(n).apply(fn); } public static A times(Integer n, Fn1 fn, A a) { return Times.times(n, fn).apply(a); } }





© 2015 - 2024 Weber Informatics LLC | Privacy Policy