内蔵クラスの利用

Object REXXには直ぐに使え、プログラムの基本的な要素の多くをカバーするクラスが初めから内蔵されている。例えばいわゆるコレクションクラスなどである。

内蔵クラスの例を挙げよう:

コレクションクラスは大量のオブジェクトの集りを、順序付けられていないバッグ、リスト、表、配列の形で扱うのに大変役立つ。順序のある文字列を扱うにはリストクラスを用いることができる。

/* create a list object for strings */
/* 文字列のリストオブジェクトを生成する */
myList = .List‾New
myList‾Insert("John")            /* add John to the list */
                                 /* Johnをリストに加える */

/* Add Bob and Anne to the end of the list. We will use  */
/* the ‾‾ operator (returning the object instead of a    */
/* result) for this purpose.                             */
/* BobとAnneをリストの最後に加える。そのため‾‾(波線2つ) */
/* 演算子を用いる。この演算子はメッセージ処理の結果の代り */
/* にオブジェクトを返す */
myList‾‾Insert("Bob")‾Insert("Anne")

/* show the number of elements in the list, should be 3  */
/* リストに含まれる要素の数を返す。3になるはず */
Say "The list now contains" myList‾Items "items."

/* show the first item in the list, should be "John"     */
/* 最初の要素を表示する。Johnになるはず */
Index = myList‾First       /* get index of first element */
Say "The first item in the list is" myList‾At(Index)

/* insert Peter following the first item in the list     */
/* Peterを2番目の要素として加える。 */
myList‾Insert("Peter", Index)  /* add Peter after index  */

/* if an item should be inserted at the top of the list  */
/* you have to specify .nil as the index                 */
/* リストの先頭に要素を潜り込ませるためには、インデックス */
/* として.nilを指定する。 */
myList‾Insert("David", .nil)
上の例では新しい特徴が使われている。一つはメッセージ送付演算子 '‾‾' である。この演算子は同じようにメッセージを送付する演算子 '‾' (一つの波線)と異なり、メッセージ処理の結果でなくメッセージが送付されたオブジェクトを返す。'‾‾'演算子は一つのオブジェクトに複数のメッセージを送付するのに使える。

サンプルの最後の演算はリストの先頭に要素を追加する。その際事前定義オブジェクト.nilを要素を追加すべきインデックスとして用いる。.nilはデータが存在しないことを表す特別なオブジェクトである。

さて、これでこれから処理する文字列のリストができた。処理は2つの方法でできる。一つは全ての要素を舐めるループで、古典的なコーディングである。リストの先頭から始めて、リストの最後に到達する('NEXT'メソッドが.nilオブジェクトを返す)まで全ての要素を出力する。

/* loop over all elements in the list and show them      */
Index = myList‾First
Do While Index ¥= .nil
  Say myList[Index]   /* equivalent to myList‾At(Index)  */
                      /* myList‾At(Index)と書いても同じ */
  Index = myList‾Next(Index) /* go to next item in list  */
End
こんな結果が出るはずである:
David
John
Peter
Bob
Anne
コレクションの全ての要素を舐めるために、Object REXXは新しい制御構造を備えた。'DO ... OVER'ループである。この命令は全てのコレクションクラス(即ち、リスト、配列、バッグ、表など)だけでなく、ストリーム(特殊な形式のコレクションとみることができる)に対しても用いることができる。使い方の例である:
/* loop over all elements in the list and show them      */
Do ListItem Over myList
  Say ListItem‾Reverse "is the reversed string of" ListItem
End
こんな結果が出るはずである:
divaD is the reversed string of David
nhoJ is the reversed string of John
reteP is the reversed string of Peter
boB is the reversed string of Bob
ennA is the reversed string of Anne
ここまでで、内蔵クラスの基本的な利用法のいくたりかを見てきた。次は自分自身のクラスを宣言してみる。
[ Previous page | Next page | Tutorial Index | ]