Skip to content

Instantly share code, notes, and snippets.

@takungsk
Created May 26, 2012 15:22
Show Gist options
  • Save takungsk/2794314 to your computer and use it in GitHub Desktop.
Save takungsk/2794314 to your computer and use it in GitHub Desktop.
scala-tips
// foldLeft と foldRight
// foldLeft
scala> List(1,2,3,4,5).foldLeft(0){(x,y) => x + y} // x が初期値、yが要素になる
res5: Int = 15
scala> List(1,2,3,4,5).foldLeft(0){(x,y) => x + x}
res6: Int = 0
scala> List(1,2,3,4,5).foldRight(0){(x,y) => x + y} // x が 要素、yが初期値になる
res8: Int = 15
scala> List(1,2,3,4,5).foldRight(0){(x,y) => x + x}
res9: Int = 2
scala> List(1,2,3,4,5).foldRight(0){(x,y) => y + y}
res10: Int = 0

zipWithIndex について

zipWithIndex

List を インデックス付きにする。

scala> List("a","b","c","d").zipWithIndex
res4: List[(java.lang.String, Int)] = List((a,0), (b,1), (c,2), (d,3))

こうすると 一気に

List("a","b","c","d","e").zipWithIndex.map{t => (t._2 + 1, t._1)}.foreach(println(_))

foldLeft を使って要素 を計算

リストの内容 * インデックス の値を足し合わせる 0 * 0 + 10 * 1 + 20 * 2 + 30 * 3 を実行

scala> List(0, 10, 20, 30).zipWithIndex.map{t => (t._1 * t._2)}.foldLeft(0)(_ + _)
res20: Int = 140
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment