Java的Monad和懒赋值

13-02-19 banq
很老的一篇文章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>

懒赋值:

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

banq注:个人在jdonframework中使用disruptor/future两种方式实现懒赋值,disruptor吞吐量要比future大些。

         

SpeedVan
2013-02-22 14:31
这样用,除了对monad熟透的人,谁敢用?

猜你喜欢