意外的 Scala 模式匹配语法 [英] Unexpected Scala pattern matching syntax

查看:48
本文介绍了意外的 Scala 模式匹配语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的 Scala 元组列表:

I had a List of Scala tuples like the following:

val l = List((1,2),(2,3),(3,4))

我想将它映射到一个 Int 列表中,其中每个项目是相应元组中 Int 的总和.我也不想使用 x._1 符号,所以我用这样的模式匹配解决了这个问题

and I wanted to map it in a list of Int where each item is the sum of the Ints in a the corresponding tuple. I also didn't want to use to use the x._1 notation so I solved the problem with a pattern matching like this

def addTuple(t: (Int, Int)) : Int = t match { 
    case (first, second) => first + second 
}
var r = l map addTuple

这样做后,我按预期获得了列表 r: List[Int] = List(3, 5, 7).在这一点上,几乎是偶然地,我发现我可以使用如下的缩写形式实现相同的结果:

Doing that I obtained the list r: List[Int] = List(3, 5, 7) as expected. At this point, almost by accident, I discovered that I can achieve the same result with an abbreviated form like the following:

val r = l map {case(first, second) => first + second}

我在我拥有的文档中找不到任何对此语法的引用.这是正常的吗?我是否遗漏了一些微不足道的东西?

I cannot find any reference to this syntax in the documentation I have. Is that normal? Am I missing something trivial?

推荐答案

请参阅语言参考的第 8.5 节模式匹配匿名函数".

See Section 8.5 of the language reference, "Pattern Matching Anonymous Functions".

匿名函数可以由一系列 case 定义

An anonymous function can be defined by a sequence of cases

{case p1 => b1 ... case pn =>bn }

显示为没有先前匹配的表达式.必须部分定义此类表达式的预期类型.对于某些 k > 0,它必须是 scala.Functionk[S1, ..., Sk, R],或者 scala.PartialFunction[S1, R],其中参数类型 S1, ..., Sk 必须完全确定,但结果类型 R 可能不确定.

which appear as an expression without a prior match. The expected type of such an expression must in part be defined. It must be either scala.Functionk[S1, ..., Sk, R] for some k > 0, or scala.PartialFunction[S1, R], where the argument type(s) S1, ..., Sk must be fully determined, but the result type R may be undetermined.

预期类型决定了它是否被转换为 FunctionNPartialFunction.

The expected type deternines whether this is translated to a FunctionN or PartialFunction.

scala> {case x => x}  
<console>:6: error: missing parameter type for expanded function ((x0$1) => x0$1 match {
  case (x @ _) => x
})
       {case x => x}
       ^

scala> {case x => x}: (Int => Int)
res1: (Int) => Int = <function1>

scala> {case x => x}: PartialFunction[Int, Int]
res2: PartialFunction[Int,Int] = <function1>

这篇关于意外的 Scala 模式匹配语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆