gpt4 book ai didi

scala - 2.9 和 2.10 中的理解不同行为

转载 作者:行者123 更新时间:2023-12-01 10:45:36 26 4
gpt4 key购买 nike

Scala 2.10 似乎更新了对 Either 的理解。在 2.10 中:

scala> val a = Right(5)
a: scala.util.Right[Nothing,Int] = Right(5)

scala> for {aa: Int <- a.right} yield {aa}
<console>:9: error: type mismatch;
found : Int => Int
required: scala.util.Either[Nothing,Int] => ?
for {aa: Int <- a.right} yield {aa}
^

在2.9.3中,以上是可以的。

scala> val a = Right(5)
a: Right[Nothing,Int] = Right(5)

scala> for {aa: Int <- a.right} yield {aa}
res0: Product with Serializable with Either[Nothing,Int] = Right(5)

只需删除 2.10 中 aa 的类型即可轻松修复。但我想知道为什么行为会在 2.9 和 2.10 之间发生变化。

最佳答案

这似乎是由于这个 open bug它添加了 withFilter,即使它不是必需的。为了解释它,一些简短的介绍:

2.10 中使用 -Xprint:typer 编译下面给出

for {aa <- a.right} yield {aa}

Temp.this.a.right.map[Int](((aa: Int) => aa))

//for below
for {aa:Int <- a.right} yield {aa}

a.right.filter[Nothing](((check$ifrefutable$1: Int) => (check$ifrefutable$1: Int @unchecked) match {
case (aa @ (_: Int)) => true
case _ => false
})).map[B](((aa: Int) => aa))

这显然是第二种情况的错误。因为总之你是doing Option[scala.util.Either[Nothing,Int]].map((aa:Int) => aa) 这是一个错误,因为它期望在 Either 上进行映射而不是 Int

Scala 2.9.3 中,对于上述两种情况,它给出:

a.right.map[Int](((aa: Int) => aa))

2.10 中添加了一个 with-filter 子句。来自 for-comprehension specs :

The translation scheme is as follows. In a first step, every generator p <- e, where p is not irrefutable for the type of e is replaced by

p <- e.withFilter { case p => true; case _ => false }

在你的第一种情况下,pIrrefutable (规范中的第 1 点)因此未添加 withFilter。在你的第二种情况下,pIrrefutable (第 2 点因此不应添加 withFilter。但它确实存在,这是一个错误。

类似阅读:why does filter have to be defined for pattern matching in a for loop in scala?

关于scala - 2.9 和 2.10 中的理解不同行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26646409/

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