意外的 Scala 模式匹配语法
我有一个如下所示的 Scala 元组列表:
val l = List((1,2),(2,3),(3,4))
我想将其映射到 Int 列表中,其中每个项目都是相应元组中 Int 的总和。我也不想使用 x._1 表示法,所以我通过像这样的模式匹配解决了问题
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) 。此时,几乎是偶然,我发现我可以使用如下所示的缩写形式获得相同的结果:
val r = l map {case(first, second) => first + second}
我在我拥有的文档中找不到对此语法的任何引用。这正常吗?我错过了一些微不足道的事情吗?
I had a List of Scala tuples like the following:
val l = List((1,2),(2,3),(3,4))
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
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
方法
map
接受一个函数。在第一个示例中,您创建一个函数,将其分配给一个变量,然后将其传递给map
方法。在第二个示例中,您直接传递创建的函数,省略将其分配给变量。你也在做同样的事情。Method
map
accepts a function. In your first example you create a function, assign it to a variable, and pass it to themap
method. In the second example you pass your created function directly, omitting assigning it to a variable. You are doing just the same thing.<代码> {案例(第一,第二)=> First + Second} 被视为
PartialFunction
文字。请参阅“部分函数”部分中的示例:http://programming-scala.labs。 oreilly.com/ch08.html 或《Scala 编程》第 15.7 节。{case(first, second) => first + second}
is treated as aPartialFunction
literal. See examples in "Partial Functions" section here: http://programming-scala.labs.oreilly.com/ch08.html or section 15.7 of Programming in Scala.请参阅语言参考的第 8.5 节“模式匹配匿名函数”。
预期类型决定是否将其转换为
FunctionN
或PartialFunction
。See Section 8.5 of the language reference, "Pattern Matching Anonymous Functions".
The expected type deternines whether this is translated to a
FunctionN
orPartialFunction
.