Matthew Pickering Matthew Pickering - 24 days ago 17
Scala Question

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?

Answer

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.

Comments