2017-07-22 20 views
1

スカラ:計算合計

var sum = 0 
for (xs <- xss; x <- xs) sum +=x 

は、この方法は副作用を持っている合計を計算する合計を計算スカラ座での簡単なコードを以下とします。副作用なしにこれをどうすればいいですか?

答えて

1

scala> val collection = List(List(1, 2, 3, 4), List(5, 6, 7, 8)) 
collection: List[List[Int]] = List(List(1, 2, 3, 4), List(5, 6, 7, 8)) 

scala> var sum = 0 
sum: Int = 0 

scala> for (xs <- collection; x <- xs) sum +=x 

scala> sum 
res4: Int = 36 

短い方法は、あなたは、コレクションにあなたが望むように折り畳まれている、

scala> collection.flatten.sum 
res7: Int = 36 

もの要素をあなたのコレクションを平らにし、合計することが、あなたのxssList of Listである可能性がありますと仮定します。

scala> collection.flatten.foldLeft(0)((a, b) => a + b) 
res9: Int = 36 

// or without flattening 
scala> collection.foldLeft(0)((a, b) => a + b.sum) 
res14: Int = 36 

またはreducedLeft

scala> collection.flatten.reduceLeft((a, b) => a + b) 
res10: Int = 36 

を持つことができますが、theresの.sumコレクションのため、あなたが.sumに行く必要があります。

+3

折りたたみ中に 'flatten'は必要ありません。' xss.foldLeft(0)(_ + _.sum) ' – jwvh

+0

@jwvh trueも同様です。 'collection.foldLeft(0)((a、b)=> a + b.sum)' Thx – prayagupd