fold list of tuples in scala with destructuring

前端 未结 2 680
南笙
南笙 2020-12-29 12:56
scala> val l = List((1,2), (2,3))
l: List[(Int, Int)] = List((1,2), (2,3))

I can do

scala>  (0 /: l) {(a, i) => i._1 + a}
         


        
相关标签:
2条回答
  • 2020-12-29 13:23

    Note that, in addition to Walter's answer, you can use the underscore _ instead of c in the pattern match:

    val i = (0 /: l) { case (a, (b, _)) => b + a }
    

    It acts as an anything goes placeholder in the Tuple2 pattern and (to my mind) makes it clearer that you don't actually use the value in your calculation.

    Also, in 2.8 you would be able to do:

    val i = l.map(_._1).sum
    
    0 讨论(0)
  • 2020-12-29 13:46

    Give this a try:

    (0 /: l) { case (a, (b, c)) => b + a }
    
    0 讨论(0)
提交回复
热议问题