アットウィキロゴ

Example13.2

「Example13.2」の編集履歴(バックアップ)一覧に戻る

Example13.2 - (2011/02/24 (木) 09:00:29) のソース

#co(){
13.2 Constructing Iterators

Concrete iterators need to provide implementations for the two abstract methods next and hasNext in class Iterator. The simplest iterator is Iterator.empty which always returns an empty sequence:
}


#setmenu2(ex-r-menu)
** 13.2 イテレータの構築 (Constructing Iterators)

具体的なイテレータは、クラス Iterator の2つの抽象メソッド next と hasNext の実装を提供する必要があります。もっとも単純なイテレータは、常に空の列を返す Iterator.empty です。

 object Iterator {
     object empty extends Iterator[Nothing] {
         def hasNext = false
         def next = error("next on empty iterator")
     }

#co(){
A more interesting iterator enumerates all elements of an array. This iterator is constructed by the fromArray method, which is also defined in the object Iterator
}

もっと面白みのあるイテレータは、配列のすべての要素を列挙するものです。このイテレータはオブジェクト Iterator で定義されている fromArray メソッドで構築されます。

     def fromArray[A](xs: Array[A]) = new Iterator[A] {
         private var i = 0
         def hasNext: Boolean =
             i < xs.length
         def next: A =
             if (i < xs.length) { val x = xs(i); i += 1; x }
             else error("next on empty iterator")
     }

#co(){
Another iterator enumerates an integer interval. The Iterator.range function returns an iterator which traverses a given interval of integer values. It is defined as follows.
}

ほかのイテレータとして、範囲内の整数を列挙するものがあります。Iterator.range 関数は、与えられた範囲の整数値をたどるイテレータを返します。

 object Iterator {
   def range(start: Int, end: Int) = new Iterator[Int] {
         private var current = start
         def hasNext = current < end
         def next = {
             val r = current
             if (current < end) current += 1
             else error("end of iterator")
             r
         }
     }
 }

#co(){
All iterators seen so far terminate eventually. It is also possible to define iterators that go on forever. For instance, the following iterator returns successive integers from some start value(*1).
}

ここまで見てきたイテレータはいずれ終わりますが、永遠に続くイテレータも定義できます。たとえば、次のイテレータは初期値からずっと続く整数を返します(*1)。

 def from(start: Int) = new Iterator[Int] {
     private var last = start 1
     def hasNext = true
     def next = { last += 1; last }
 }


#co(){
(*1) Due to the finite representation of type int, numbers will wrap around at 2^31.
}

(*1) int 型が有限の表現であるため、2^31で数は元に戻ります。

#center(){[[前ページ>Example13.1]] [[ 13 章>Chapter 13 Iterators]] [[目次>ScalaByExample和訳]] [[次ページ>Example13.3]]}

----
#comment
ツールボックス

下から選んでください:

新しいページを作成する
ヘルプ / FAQ もご覧ください。