B): F[B] } def Vecto-6ren">
gpt4 book ai didi

scala - 来自 "Scala in Action"的类型投影示例(第 8 章)

转载 作者:行者123 更新时间:2023-12-04 20:10:26 24 4
gpt4 key购买 nike

任何人都可以帮助我解决书中的以下代码位吗?

trait Mapper[F[_]] {
def fmap[A, B](xs: F[A], f: A => B): F[B]
}

def VectorMapper = new Mapper[Vector] {
def fmap[A, B](xs: Vector[A], f: A => B): Vector[B] = xs map f
}

这很简单:使用更高类型的特征定义 F[_]用于任何“容器类”类型,然后是 Vector 的具体映射器.

然后是一个棘手的部分。 Either 的映射器.
我了解 {type E[A] = Either[X, A]}就像一段代码,和 ({type E[A] = Either[X, A]})#E作为采用该类型别名 E 的投影从匿名代码块中,作者“隐藏”了 X 的存在对于 Mapper trait 因为 trait 仅对单个类型参数“容器类型”进行操作 - 我们对 A 感兴趣,即 Right .
def EitherMapper[X] = new Mapper[({type E[A] = Either[X, A]})#E ] {
def fmap[A, B](r: Either[X, A], f: A => B): Either[X, B] = r match {
case Left(a) => Left(a)
case Right(a) => Right(f(a))
}
}

问题:
为什么我们需要 Xdef EitherMapper[X] =部分?

感谢您提供详细信息。

最佳答案

要么取决于两种类型,例如 Either[Int, String]EitherMapper是一个只依赖于一种类型的类型构造函数,所以当你有一个 EitherMapper[Int] ,您正在处理 Either[Int, A] , 和 A被解析到 Mapper 部分,这样你可以有任何 A=>B函数,因为第一种类型 Either映射器已经存在,您返回 Either[X, B] .

事实上,类型 E[A] 等价于 Either[X, A],关于类型,你只有一个自由度!

val right: Either[Boolean, String] = Right("test")
val left: Either[Boolean, String] = Left(false)

println(EitherMapper.fmap(right, (s: String) => s.length))
> Right(4)
println(EitherMapper.fmap(left, (s: String) => s.length))
> Left(false)

在这种情况下,类型是 EitherMapper[Boolean] fmap 的类型是 fmap[String, Integer] , 它接受 Either[Boolean, String]并返回 Either[Boolean, Integer] .

如您所见,fmap 的类型在 X 上没有说明。 Either[X, A] 的一部分所以最后你可以使用 (s: String) => s.length)为他人服务 EitherMapper[X]类型,简单来说,任何一种类型的“左”部分都可以是您想要的任何东西,它是类型构造的“X”部分。

希望现在更清楚了!

关于scala - 来自 "Scala in Action"的类型投影示例(第 8 章),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18174008/

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