Example13.3

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

Example13.3 - (2011/02/24 (木) 09:03:50) のソース

#co(){
13.3 Using Iterators

Here are two more examples how iterators are used. First, to print all elements of an array xs: Array[Int], one can write:
}


#setmenu2(ex-r-menu)
** 13.3 イテレータの使用 

イテレータの使い方の例をさらに2つあげます。最初は、配列 xs: Array[Int]のすべての要素を表示するもので、次のように書けます。

 Iterator.fromArray(xs) foreach (x => println(x))

#co(){
Or, using a for-comprehension:
}

または for 内包表記を使っても書けます。

 for (x <Iterator.fromArray(xs))
     println(x)

#co(){
As a second example, consider the problem of finding the indices of all the elements in an array of doubles greater than some limit. The indices should be returned as an iterator. This is achieved by the following expression.
}

二つ目の例として、double の配列のうち、要素がある値より大きいすべてのインデックスを求めることを考えます。インデックスはイテレータとして返されるものとします。これは、次の式で実現できます。

 import Iterator._
 fromArray(xs)
 .zip(from(0))
 .filter(case (x, i) => x > limit)
 .map(case (x, i) => i)

#co(){
Or, using a for-comprehension:
}

または for 内包表記を使っても実現できます。

 import Iterator._
 for ((x, i) <fromArray(xs) zip from(0); x > limit)
 yield i

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

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

下から選んでください:

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