summaryrefslogtreecommitdiff
path: root/base/src/main/java/bjc/utils/funcutils/Callables.java
diff options
context:
space:
mode:
authorBenjamin J. Culkin <bjculkin@mix.wvu.edu>2020-12-14 19:29:37 -0400
committerBenjamin J. Culkin <bjculkin@mix.wvu.edu>2020-12-14 19:29:37 -0400
commit9351ea3e97bbe2d348aa17067ccc6267dc7c080f (patch)
treedd2269c26161c735d94d8dc83d56e6076c2a155d /base/src/main/java/bjc/utils/funcutils/Callables.java
parent8933de7f646f0565edf700aa2f2fcab06d639855 (diff)
parent6dcadc360dafdd12142d53327f44579379a4c9dd (diff)
Merge branch 'master' of https://github.com/bculkin2442/bjc-utils2
Diffstat (limited to 'base/src/main/java/bjc/utils/funcutils/Callables.java')
-rw-r--r--base/src/main/java/bjc/utils/funcutils/Callables.java60
1 files changed, 60 insertions, 0 deletions
diff --git a/base/src/main/java/bjc/utils/funcutils/Callables.java b/base/src/main/java/bjc/utils/funcutils/Callables.java
new file mode 100644
index 0000000..5895347
--- /dev/null
+++ b/base/src/main/java/bjc/utils/funcutils/Callables.java
@@ -0,0 +1,60 @@
+package bjc.utils.funcutils;
+
+import java.util.concurrent.*;
+import java.util.function.*;
+
+/**
+ * Utility function for dealing with callables and other things.
+ *
+ * @author Ben Culkin
+ *
+ */
+public class Callables
+{
+ /**
+ * Perform a 'bind' that appends a function to a callable.
+ *
+ * @param <Input> The type originally returned by the callable.
+ * @param <Output> The type returned by the function.
+ *
+ * @param call The original callable.
+ * @param func The function to use to transform the result.
+ *
+ * @return A callable which applies the given function to the result of them.
+ */
+ public static <Input, Output> Callable<Output> bind(
+ Callable<Input> call, Function<Input, Callable<Output>> func)
+ {
+ return () -> func.apply(call.call()).call();
+ }
+
+ /**
+ * Convert a normal function to a function on callables.
+ *
+ * @param <Input> The input to the function.
+ * @param <Output> The output from the function.
+ *
+ * @param func The function to convert.
+ *
+ * @return The function, made to work over callables.
+ */
+ public static <Input, Output> Function<Callable<Input>, Callable<Output>>
+ fmap(Function<Input, Output> func)
+ {
+ return (inp) -> () -> func.apply(inp.call());
+ }
+
+ /**
+ * Convert a future into a callable.
+ *
+ * @param <Output> The type returned by the future.
+ *
+ * @param fut The future to convert.
+ *
+ * @return A future which yields that value.
+ */
+ public static <Output> Callable<Output> obtain(Future<Output> fut)
+ {
+ return () -> fut.get();
+ }
+}