【发布时间】:2014-07-28 09:48:21
【问题描述】:
我目前正在试验 Java 8 的 Future API 和 Core CompleteableFuture。我知道它是一个 monad,所以它应该有一个 bind-Operator。
现在的想法是我有一个抽象操作 k 的树,例如像这样:
O --- > O3 ---> O4 ---> o5
O ---> o2 --/
我想将O3 和O2“合并”成一个新的操作O4 = (O3 o O2) (t) = O2(O3(t))。
我的想法是我是例如在O2 中并想说:将当前节点与O3 合并,并返回一个由串联操作组成的新节点。
不幸的是,我已经尝试了一整晚,但我无法弄清楚。
此外,由于未知原因,使用 O1.mergeWith(O2).mergeWith(O3) 之类的运算符会触发 apply 方法两次以进行单次调用。
目标是创建一个由其他函数组成的新函数,所以我可以尽可能推迟计算。
public abstract class Operation<T,R> {
// The value a
private final CompletableFuture<R> future;
// Executes the operation on t and returns something (maybe different) of type R
protected abstract R apply(T t);
// Gets the value of the future of this operation
public R get() throws Exception {
return future.get();
}
protected Operation(Supplier<T> s) {
future = CompletableFuture.supplyAsync(s).thenApplyAsync(transform());
}
protected Operation(CompletableFuture<R> f) {
future = f;
}
CompletableFuture<R> createTargetFuture(R _value) {
return CompletableFuture.supplyAsync(() -> _value);
}
<S> Operation<T,S> mergeWith(Operation<R,S> _other) {
CompletableFuture<S> _result = future.thenComposeAsync(
// Method is synchronous, but is run async :) We need the createTargetFuture, otherwise we cannot turn the constant t into a producer.
(t) -> _other.createTargetFuture(_other.apply(t)));
//transform()).thenApplyAsync(_other.transform());
return new Operation<T, S>(_result) {
@Override
protected S apply(T t) {
// What to put here
return null;
}
};
}
protected Function<T,R> transform(){
return this::apply;
}
}
【问题讨论】:
标签: java functional-programming monads java-8