LoginSignup
3
3

More than 5 years have passed since last update.

ScalaのfoldLeftとscanLeft

Last updated at Posted at 2015-04-11

foldLeftとscanLeft

foldLeftは処理後の値一つを返すのに対しscanLeftは処理毎の途中結果をコレクションとして返してくれる便利なやつ。処理毎の履歴が必要な時に使えそうです。

1から100までの足し算をfoldLeftとscanLeftでそれぞれで行ってみると、foldLeftは最終的な処理結果のみが返ってきているのに対しscanLeftでは途中結果が保存されているので必要な時に途中結果を取り出すことができます。

NumberSum.scala
object NumberSum {
  def main(args: Array[String]): Unit = {
    val sumfold = (1 to 100).foldLeft(0)(_ + _)
    // 5050
    val sumscan = (1 to 100).scanLeft(0)(_ + _)
    // Vector(0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120, 136, 153, 171, 190, 210, 231, 253, 276, 300, 325, 351, 378, 406, 435, 465, 496, 528, 561, 595, 630, 666, 703, 741, 780, 820, 861, 903, 946, 990, 1035, 1081, 1128, 1176, 1225, 1275, 1326, 1378, 1431, 1485, 1540, 1596, 1653, 1711, 1770, 1830, 1891, 1953, 2016, 2080, 2145, 2211, 2278, 2346, 2415, 2485, 2556, 2628, 2701, 2775, 2850, 2926, 3003, 3081, 3160, 3240, 3321, 3403, 3486, 3570, 3655, 3741, 3828, 3916, 4005, 4095, 4186, 4278, 4371, 4465, 4560, 4656, 4753, 4851, 4950, 5050)
  }
}

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3