Labra Labra - 2 months ago 10
Scala Question

How to define local method on top of a monad transformer stack in Scala cats

I have a monad transformer stack on top of a Kleisli defined as:

type Env = Map[String,Int]
type MyState = List[Int]
type S[A] = EitherT[StateT[WriterT[Kleisli[List,Env,?],String,?],MyState,?], String, A]


and I want to define a
local
method with the following signature:

def localE[A](f: Env => Env)(sa: S[A]): S[A] = ???


Is it possible?

I know that there is a
local
method in
MonadReader
with the signature:

def local[A](f: R => R)(fa: F[A]): F[A]


So the simplest solution would be to obtain the
MonadReader
implicit from
S
, however, I could not find how to do it.

A simple snippet of my code would be the following:

package examples
import cats._, data._
import cats.implicits._

object local {
type Env = Map[String,Int]
type MyState = List[Int]
type S[A] = EitherT[StateT[WriterT[Kleisli[List,Env,?],String,?],MyState,?], String, A]

// The following definition doesn't compile
// implicit lazy val mr = MonadReader[S,Env]

// Modify the environment
def localE[A](f: Env => Env)(sa: S[A]): S[A] = ???
}

Answer

A possible solution is to unlift the monad stack manually. In this case, I defined the following two auxiliary functions:

  def localW[A](f: Env => Env)
               (c: WriterT[Kleisli[List,Env,?],String,A]): 
         WriterT[Kleisli[List,Env,?],String,A] = {
   type WriterTF[F[_],A] = WriterT[F, String, A]
   val r: WriterT[Kleisli[List,Env,?],String,(String,A)] = 
      c.run.local(f).liftT[WriterTF]
   r.mapBoth { case (_, (w, x)) => (w, x) }
 }

   def localS[A](f: Env => Env)
                (c: StateT[WriterT[Kleisli[List,Env,?],String,?],MyState,A]): 
        StateT[WriterT[Kleisli[List,Env,?],String,?],MyState,A] = {
  StateT(s => localW(f)(c.run(s)))
  }

And the local function can be defined as:

  def localE[A](f: Env => Env)(sa: S[A]): S[A] = {
     EitherT(localS(f)(sa.value))
  }
Comments