LoginSignup
26
19

More than 5 years have passed since last update.

インデックス付きでリストを処理する

Last updated at Posted at 2012-07-15

リスト(A, B, C)みたいなデータがあったときに,そのインデックス(Aなら0,Bなら1,Cなら2)を一緒に扱って処理したい,ということがよくありました.今まではそのためにわざわざ

imamade.scala
val list = List("A", "B", "C")
for (i <- 0 until list.length) {
  println(i, list(i))
}

のような少し残念な書き方をしていたのですが,ScalaにはちゃんとzipWithIndexという関数がありました.おそらくcollectionでSeq系なら使えるような気がする関数で,インデックスを一緒に包んでタプルのリストを作ってくれます.

motto_smart.scala
val list = List("A", "B", "C")
// list.zipWithIndex
// res6: List[(java.lang.String, Int)] = List((A,0), (B,1), (C,2))

val array = Array("a", "b", "c")
// array.zipWithIndex
// res4: Array[(java.lang.String, Int)] = Array((a,0), (b,1), (c,2))

// how to use
list.zipWithIndex.foreach { v => println(v._1, v._2)}
list.zipWithIndex.foreach { case(e:String, i:Int) => println(i, e) }

とてもすっきりしました.やはり標準のライブラリをちゃんと調べるといいことがありますね.

26
19
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
26
19