简体   繁体   中英

Monad Transformers in Scala

I have been trying simple Monad Transformers where I have for comprehensions involving M[F[A]] where M and F are monads. How can I make M[F[A]] and M[S[A]] work together in a for comp if S is a different monad?

For example:

val a: Future[List[Int]] = ...
val b: Future[Option[Int]] = ...

a requires a ListT[Future, Int] and b requires an OptionT[Future, Int] but these do not compose, do I need to use another transformer? Would this depend on the order I use them in the for comp?

Monad Transformers help you in composing two values of type F[G[X]] .

In other terms, monad transformers work with F[G[X]] because they leverage the fact that you know how to compose two G[X] if Monad[G] exists.

Now, in case of F[G[X] and F[H[X]] , even if you state that G and H have Monad instances, you still don't have a general way of composing them.

I'm afraid composing F[G[X]] and F[H[X]] has no general solution with monad transformers.

You could try using a monad transformer stack ListT[OptionT[Future, Int]] which combines all effects at once. You can lift a and b into values of that monad transformer stack.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM