隐式找不到功能

时间:2019-03-24 21:36:17

标签: scala simulacrum

我有这个类型类

import simulacrum._
@typeclass trait Functor[F[_]] {
    def map[A, B](fa: F[A])(f: A => B) : F[B]
    def lift[A, B](fa: F[A])(f: A => B) : F[A] => F[B] = fa => map(fa)(f)
    def as[A, B](fa: F[A], b: => B) : F[B] = map(fa)(_ => b)
    def void[A](fa: F[A]) : F[Unit] = as(fa, ())
}

这是实现

object Functor {
    implicit val listFunctor: Functor[List] = new Functor[List] {
        def map[A, B](fa: List[A])(f: A => B) = fa.map(f)
    }
    implicit def functionFunctor[X]: Functor[X => ?] = new Functor[X => ?] {
        def map[A, B](fa : X => A)(f : A => B) = fa andThen f
    }
}

我可以轻松地发现List隐式实现为

object Chapter1 extends App {
    import Functor.ops._
    List(1, 2, 3).as("foo").foreach(println)
}

以上工作正常。我也可以做

object Chapter1 extends App {
    import Functor._
    val func : Int => String = implicitly[Functor[Int => ?]].map(_ + 2)(_.toString)
    println(func(5))
}

但是当我尝试

object Chapter1 extends App {
    import Functor.ops._
    val x : Int => Int = _ + 2
    val y : Int => String = x.map(_.toString)
}

找不到我的隐式实现,并说值map不是Int => Int的成员

1 个答案:

答案 0 :(得分:3)

编译器看不到Int => Int被应用到Int => ?上。

添加

Int

以构建.sbt。

对于使用Cats,Scalaz或手动进行的更高种类的类型的正常工作是必要的。

顺便说一句,scalacOptions += "-Ypartial-unification" 毫无意义