未找到函数的隐式
Implicit for Function not being found
我有这个类型
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
的成员
编译器看不到 Int => Int
是 Int => ?
应用于 Int
。
添加
scalacOptions += "-Ypartial-unification"
至build.sbt。
使用 Cats、Scalaz 或手动处理较高类型的正常工作是必要的。
顺便说一句,import Functor._
没有意义
我有这个类型
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
编译器看不到 Int => Int
是 Int => ?
应用于 Int
。
添加
scalacOptions += "-Ypartial-unification"
至build.sbt。
使用 Cats、Scalaz 或手动处理较高类型的正常工作是必要的。
顺便说一句,import Functor._