How to work with Reader [A, Future [B]]

Given the following 3 functions,

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] = ???

How to write a monadic combinator?

Here is my current solution, but I'm not very happy with all of these patterns

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)
+4
source share
1 answer
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)

I am not sure if there is a better way to replace mapK[Future, C](identity).

+2
source

Source: https://habr.com/ru/post/1623748/


All Articles