diff options
| author | Benjamin J. Culkin <bjculkin@mix.wvu.edu> | 2017-10-08 22:39:59 -0300 |
|---|---|---|
| committer | Benjamin J. Culkin <bjculkin@mix.wvu.edu> | 2017-10-08 22:39:59 -0300 |
| commit | c82e3b3b2de0633317ec8fc85925e91422820597 (patch) | |
| tree | 96567416ce23c5ce85601f9cedc3a94bb1c55cba /base/src/main/java/bjc/utils/funcutils/FuncUtils.java | |
| parent | b3ac1c8690c3e14c879913e5dcc03a5f5e14876e (diff) | |
Start splitting into maven modules
Diffstat (limited to 'base/src/main/java/bjc/utils/funcutils/FuncUtils.java')
| -rw-r--r-- | base/src/main/java/bjc/utils/funcutils/FuncUtils.java | 76 |
1 files changed, 76 insertions, 0 deletions
diff --git a/base/src/main/java/bjc/utils/funcutils/FuncUtils.java b/base/src/main/java/bjc/utils/funcutils/FuncUtils.java new file mode 100644 index 0000000..9950add --- /dev/null +++ b/base/src/main/java/bjc/utils/funcutils/FuncUtils.java @@ -0,0 +1,76 @@ +package bjc.utils.funcutils; + +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.UnaryOperator; + +/** + * Utility things for functions + * + * @author ben + * + */ +public class FuncUtils { + /** + * Convert a binary function into a unary function that returns a + * function + * + * @param <A> + * The initial type of the function + * @param <B> + * The intermediate type of the function + * @param <C> + * The terminal type of the function + * @param func + * The function to transform + * @return The function transformed into a unary function returning a + * function + */ + public static <A, B, C> Function<A, Function<B, C>> curry2(final BiFunction<A, B, C> func) { + return arg1 -> arg2 -> { + return func.apply(arg1, arg2); + }; + } + + /** + * Do the specified action the specified number of times + * + * @param nTimes + * The number of times to do the action + * @param cons + * The action to perform + */ + public static void doTimes(final int nTimes, final Consumer<Integer> cons) { + for (int i = 0; i < nTimes; i++) { + cons.accept(i); + } + } + + /** + * Return an operator that executes until it converges. + * + * @param op + * The operator to execute. + * @param maxTries + * The maximum amount of times to apply the function in an + * attempt to cause it to converge. + */ + public static <T> UnaryOperator<T> converge(final UnaryOperator<T> op, final int maxTries) { + return (val) -> { + T newVal = op.apply(val); + T oldVal; + + int tries = 0; + + do { + oldVal = newVal; + newVal = op.apply(newVal); + + tries += 1; + } while(!newVal.equals(oldVal) && tries < maxTries); + + return newVal; + }; + } +} |
