0
votes

I'm learning scalaz these days. When I compare scalaz with Haskell, I find that it's hard to customize my own monad transformer.

The code I can do in Haskell like this:

newtype Box a = Box a deriving Show
-- Monad instance of Box, it's simple, I pass it..
newtype BoxT m a = BoxT {runBoxT :: m (Box a)}

instance (Monad m) => Monad (BoxT m) where
    return a = BoxT $ return $ Box a
    x >>= f = BoxT $ do
        (Box v) <- runBoxT x
        runBoxT $ f v

instance (Monad m) => Applicative (BoxT m) where
    pure = return
    (<*>) = ap

instance (Monad m) => Functor (BoxT m) where
    fmap = liftM

How can I do the same thing in scalaz ? I have tried many ways, but it looks like I can not figure out the type of scala's generic, like this:

case class Box[A](value:A)
case class BoxT[M[_],A](run: M[Box[A]])

implicit val monad = Monad[BoxT] { // goes wrong, type `BoxT[M[_],A]` doesn't match F[_]
 ... //don't know how to override functions..
}

1
Have you tried using synthetic class ? or * like it done for OptionT in cats? Like line 284 here. github.com/typelevel/cats/blob/master/core/src/main/scala/cats/… Also you can look at type lambdas underscore.io/blog/posts/2016/12/05/type-lambdas.htmlIva Kam
emm, It's a little weird, I tried ? and ', but the compiler says not found: type *, I have no idea.. My scala version is 2.13.1, sbt is 1.2.8, java is openjdk-11Jacky Wong
You have kind projector enabled?Iva Kam
Oh thx, I think I work it out, I'll post my solution then.Jacky Wong

1 Answers

1
votes

Thanks for @Iva Kam's comment about kind projector.

First of all, enabled kind projector in build.sbt : https://github.com/typelevel/kind-projector

addCompilerPlugin("org.typelevel" %% "kind-projector" % "0.11.0" cross CrossVersion.full)

Then the code can work like this:

  case class Box[A](value:A)
  case class BoxT[M[_],A](run: M[Box[A]])

  implicit def monad[M[_]](implicit m : Monad[M]): Monad[BoxT[M, ?]] = new Monad[BoxT[M,?]] {
    override def point[A](a: => A): BoxT[M,A] = BoxT(m.point(Box(a)))

    override def bind[A, B](fa: BoxT[M,A])(f: A => BoxT[M,B]): BoxT[M,B] = BoxT(m.bind(fa.run){ b: Box[A] =>
      val v = b.value
      f(v).run
    })
  }

  def main(args: Array[String]): Unit = {
    val a = Monad[BoxT[Option,?]].point(2)
    val b = for {
      v <- a  //v should be a Int, but idea can't analyze it, maybe I should update, still in 2018.2
    } yield {v * 4}

    val c = a >> b //this line works, but idea can't analyze it :(
    println(b)
    println(c)
  }

But it looks like when I use BoxT's Monad, I should take ? instead of A of Box's inner type.