gpt4 book ai didi

Scala for comprehensions 和 partial map

转载 作者:行者123 更新时间:2023-12-02 07:51:52 25 4
gpt4 key购买 nike

Scala 语言规范部分 6.19 说:

A for comprehension for (p <- e) yield e0 is translated to e.map { case p => e0 }

所以...

scala> val l : List[Either[String, Int]] = List(Left("Bad"), Right(1))
l: List[Either[String,Int]] = List(Left(Bad), Right(1))

scala> for (Left(x) <- l) yield x
res5: List[String] = List(Bad)

到目前为止还不错:

scala> l.map { case Left(x) => x }
<console>:13: warning: match is not exhaustive!
missing combination Right

l.map { case Left(x) => x }
^
scala.MatchError: Right(1)
at $anonfun$1.apply(<console>:13)
at ...

为什么第二个版本不行?或者更确切地说,为什么第一个版本有效?

最佳答案

如果您在 for 中使用模式匹配 - 理解,编译器实际上会在应用之前插入一个带有 instanceOf 的对 filter 的调用 - 检查 map

编辑:

还在第 6.19 节中说:

A generator p <- e followed by a guard if g is translated to a single generator p <- e.withFilter((x1, ..., xn) => g ) where x1, ..., xn are the free variables of p.

生成器之前定义为:

Generator ::= Pattern1 ‘<-’ Expr [Guard]

检查字节码时,您会看到在调用 map 之前调用了 filter

关于Scala for comprehensions 和 partial map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3344404/

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