How to map and flatmap a composition of cats free monad and ZIO

177 views Asked by At

guys. I am currently trying to build a ZIO based application.

Question:

Is there any way to map and flatmap a composition of cats free monad and ZIO like the example below?

// Suppose we have a free monad like this
sealed trait SomeFMA[A]
type SomeFM[A] = Free[SomeFMA, A]

// and methods like these
def fnA: URIO[Has[D], SomeFM[Int]] = ???
def fnB: URIO[Has[E], SomeFM[Int]] = ???

// This is what I'd like to achieve
def program: URIO[Has[D] with Has[E], SomeFM[Int]] = for {
  a <- fnA
  b <- fnB
} yield a + b

What I have tried:

I know the example above does not work. You have to have a monad transformer to extract a value from a composed monad. So, I tried to use FreeT to make it possible.

type SomeFMT[M[_], A] = FreeT[SomeFMA, M, A]

def fnA: SomeFMT[URIO[Has[D], *], Int] = ???
def fnB: SomeFMT[URIO[Has[E], *], Int] = ???

// Main program (throws a type mismatch error)
def program: SomeFMT[URIO[Has[D] with Has[E], *], Int] = for {
  a <- fnA
  b <- fnB
} yield a + b

The example above throws a compilation error saying type mismatch. The dependency types are not merged in the ZIO environment type parameter.

SomeFMT[URIO[Has[D] with Has[E], *], Int] // expected return type
SomeFMT[URIO[Has[E], *], Int] // actual return type

I am completely stuck at this point. I really appreciate if you guys could help me with this!

0

There are 0 answers