Java的Monad和懶賦值

banq發表於2013-02-19
很老的一篇文章Higher-Order Java Parallelism, Part 1: Parallel Strategies and the Callable Monad

如果不願意使用Scala,也可以使用Java實現函式語言Erlang和 Parallel Haskell中併發monad和懶賦值:
Monad寫法:

 public static <A, B> F<Callable<A>, Callable<B>> fmap(final F<A, B> f) {
    return new F<Callable<A>, Callable<B>>() {
      public Callable<B> f(final Callable<A> a) {
        return bind(a, new F<A, Callable<B>>() {
          public Callable<B> f(final A ab) {
            return new Callable<B>() {
              public B call() {
                return f.f(ab);
              }
            };
          }
        });
      }
    };
  }
<p class="indent">


懶賦值:

public static <A> Callable<A> obtain(final Future<A> x) {
    return new Callable<A>() {
      public A call() throws Exception {
        return x.get();
      }
    };
  }
<p class="indent">


banq注:個人在jdonframework中使用disruptor/future兩種方式實現懶賦值,disruptor吞吐量要比future大些。

相關文章