如何处理读者[A,未来[B]]

时间:2016-01-11 12:20:41

标签: scala scalaz

鉴于以下3个功能,

def f[A, B] : Reader[A, B] = ???
def g[A, B, C](b: B) : Reader[A, Future[C]] = ???
def h[A, C, D](c: C) : Reader[A, D] = ???

如何编写monadic组合器?

这是我目前的解决方案,但我并不满意所有这些样板

def f2[A, B] : ReaderT[Future, A, B] = kleisli {
  a => Future.successful(f.run(a))
}

def h2[A, C, D](c: C) : ReaderT[Future, A, D] = kleisli {
  a => Future.successful(h(c).run(a))
}

def g2[A, B, C](b: B) : ReaderT[Future, A, C] = kleisli {
  a => g(b).run(a)
}

def i[A,B,C,D] : ReaderT[Future, A, (B,C,D)] =
  for {
    b <- f2[A, B]
    c <- g2[A, B, C](b)
    d <- h2[A, C, D](c)
  } yield (b,c,d)

1 个答案:

答案 0 :(得分:2)

def i[A,B,C,D] : ReaderT[Future, A, (B,C,D)] =
  for {
    b <- f[A, B].lift[Future]
    c <- g[A, B, C](b).mapK[Future, C](identity)
    d <- h[A, C, D](c).lift[Future]
  } yield (b,c,d)

我不确定是否有更好的方法来替换mapK[Future, C](identity)