Sequence Comprehensions
シーケンス内包表記?は、以下のように書ける。
scala> for (i <- List.range(1, 10) if i % 2 == 0) yield i res1: List[Int] = List(2, 4, 6, 8)
以下のように使用することができる。
scala> val L = for (i <- List.range(0, 10) if i % 2 == 0) yield i L: List[Int] = List(0, 2, 4, 6, 8) scala> L.foreach {i => println(i)} 0 2 4 6 8 scala> for (i <- List.range(0, 10) if i % 2 == 0) { | println(i) | } 0 2 4 6 8
yield を使用すると内部イテレータになり、式を直接書いても良い。変数 i に val を付けなくて良い理由は分からない。
1から10までのリストっぽいものを表すには以下のような方法がある。他にもあるかも。
scala> 1 to 10 res5: Range.Inclusive = Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) scala> 1 until 11 res6: Range = Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) scala> List.range(1, 11) res7: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) scala> Array.range(1, 11) res8: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) scala> Iterator.range(1, 11) res9: Iterator[Int] = has scala> Stream.range(1, 11) res10: Stream[Int] = Stream(1, ?) scala> List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) res11: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) scala> Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) res12: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
色々やり方があるのはMix-inしているからだろうけど、非常にRubyっぽいなあ。