gpt4 book ai didi

scala - 即使在使用类型投影后为 Either 声明 Functor 时出现编译错误

转载 作者:行者123 更新时间:2023-12-01 11:19:00 26 4
gpt4 key购买 nike

我正尝试在 Scala 中为 Either 编写一个 Functor 用于学术目的。在 higher-kinded 类型和 type-projections 的帮助下,我设法为 Either 编写了一个实现。

trait Functor[F[_]] {
def map[A, B](fa: F[A])(f: A => B): F[B]
}

object Functor {
implicit def eitherFunctor[A] = new Functor[({type λ[α] = Either[A, α]})#λ] {
override def map[B, C](fa: Either[A, B])(f: B => C) = fa.map(f)
}
}

def mapAll[F[_], A, B](fa: F[A])(f: A => B)(implicit fe: Functor[F]): F[B] = fe.map(fa)(f)

val right: Either[String, Int] = Right(2)

mapAll(right)(_ + 2)

现在,上面的代码无法编译。我不确定原因,但我得到的编译错误在下面给出 -

Error:(19, 16) type mismatch;
found : Either[String,Int]
required: ?F[?A]
Note that implicit conversions are not applicable because they are ambiguous:
both method ArrowAssoc in object Predef of type [A](self: A)ArrowAssoc[A]
and method Ensuring in object Predef of type [A](self: A)Ensuring[A]
are possible conversion functions from Either[String,Int] to ?F[?A]
mapAll(right)(_ + 2)

有人可以指出我在上面的代码中做错了什么吗?

PS:请不要建议我使用kind-projector

最佳答案

你刚刚被 SI-2712 咬伤了。如果您使用的是 Scala >= 2.12.2,只需将此行添加到您的 build.sbt:

scalacOptions += "-Ypartial-unification"

对于其他 Scala 版本,您可以使用 this plugin .

关于scala - 即使在使用类型投影后为 Either 声明 Functor 时出现编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46406233/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com