scala 关键字优先级

发布于 2024-10-18 07:39:43 字数 531 浏览 4 评论 0原文

scala 中如何定义“关键字优先级”?

考虑这段代码:

for(i <- 1 to 10) yield i

这没关系,我得到一个从 1 到 10 的 Seq,但是当我尝试立即匹配时:

for(i <- 1 to 10) yield i match {case x => x.head}

出现编译错误:error: value head is not Int 的成员。

我可以将 for ... yield 括在括号中以赋予其优先级:

{for(i <- 1 to 10) yield i} match {case x => x.head}

但我仍然想知道第二个示例代码是如何解释的。我希望第二个示例也能正常工作,而无需用括号括起来。

任何人都可以向我解释它或指出我在规范中的正确章节吗?

how is "keyword precedence" defined in scala?

Consider this piece of code:

for(i <- 1 to 10) yield i

This is OK, I get a Seq from 1 to 10, but when i try to match right after:

for(i <- 1 to 10) yield i match {case x => x.head}

There is a compile error: error: value head is not a member of Int.

I can surround for ... yield in parentheses to give it precedence:

{for(i <- 1 to 10) yield i} match {case x => x.head}

But I'm still wondering how is the second example code interpreted. I would expect the second example to work properly as well, without surrounding it with parens.

Can anyone explain it to me or point me to the right chapter in specification?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

半衬遮猫 2024-10-25 07:39:43

第二个示例解释为:

for(i <- 1 to 10) yield { i match {case x => x.head} } // won't compile

for 的近似语法如下:

for (Enumerators) yield Expr

Since i match { case x => x.head } 解析为有效的表达式(令牌明智),这就是编译器将如何看待它。因此,如果 Expr 看起来像一个表达式,那么它就会被处理。根据这个推理,以下语句是有效的:

for(i <- 1 to 10) yield for(j <- 1 to 2) yield (i, j)
for(i <- 1 to 10) yield if (i % 2 == 0) 'a' else 'b'
for(i <- 1 to 10) yield try { 1 / (i - 5) } catch { case _ => }

并且它们都等同于

for(i <- 1 to 10) yield { for(j <- 1 to 2) yield (i, j) }
for(i <- 1 to 10) yield { if (i % 2 == 0) 'a' else 'b' }
for(i <- 1 to 10) yield { try { 1 / (i - 5) } catch { case _ => } }

注意:Scala 语言规范可用 这里(第一个链接)。相关部分位于 A 章(Scala 语法摘要)的第 161 页。

The second example is interpreted as:

for(i <- 1 to 10) yield { i match {case x => x.head} } // won't compile

The approximate syntax for for is like:

for (Enumerators) yield Expr

Since i match { case x => x.head } parses as a valid expression (token wise), that's how the compiler will see it. So if Expr looks like an expression, that's how it will be treated. By that reasoning, the following statements are valid:

for(i <- 1 to 10) yield for(j <- 1 to 2) yield (i, j)
for(i <- 1 to 10) yield if (i % 2 == 0) 'a' else 'b'
for(i <- 1 to 10) yield try { 1 / (i - 5) } catch { case _ => }

and they are all equivalent to

for(i <- 1 to 10) yield { for(j <- 1 to 2) yield (i, j) }
for(i <- 1 to 10) yield { if (i % 2 == 0) 'a' else 'b' }
for(i <- 1 to 10) yield { try { 1 / (i - 5) } catch { case _ => } }

Note: the Scala Language Specification is available here (first link). The relevant section is on page 161 in the Chapter A (Scala Syntax Summary).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文