【问题标题】:In Scala, how do I assign the tuple values to variables in a binary operation of Map? [duplicate]在 Scala 中,如何将元组值分配给 Map 二进制操作中的变量? [复制]
【发布时间】:2012-10-07 03:51:48
【问题描述】:

可能重复:
Tuple Unpacking in Map Operations

假设我有以下 Map[Int,Double]:

scala> map
res19: scala.collection.immutable.Map[Int,Double] = Map(1 -> 1.1, 2 -> 2.2)

我可以在上面运行以下 foldLeft:

scala> map.foldLeft("A")((initVal,x:(Int,Double)) => initVal + x._1)
res20: java.lang.String = A12

但我找不到将元组的值分配给命名变量的方法:

scala> map.foldLeft("A")((init,x:(a:Int,b:Double)) => init + x.a)
<console>:1: error: ')' expected but ':' found.
   map.foldLeft("A")((init,x:(a:Int,b:Double)) => init + x.a)
                               ^

这还能做到吗?

【问题讨论】:

    标签: scala map tuples


    【解决方案1】:

    你可以用例

    map.foldLeft("A") {case (init, (a,b)) => init + a}
    

    【讨论】:

    • 非常酷。那么这种技术的正式名称是什么?所以我可以阅读它。
    • 我认为它被正式称为解构绑定。 This article 在这里提供了一些关于它是如何使用的见解。
    • 是模式匹配的一种形式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-19
    • 2012-12-30
    • 2020-11-12
    • 2021-06-14
    • 2011-10-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多