サーチ…
備考
コンパイラがforeachに遭遇した場合
foreach (element; range) {
それは内部的に次のような書き換えられます:
for (auto it = range; !it.empty; it.popFront()) {
auto element = it.front;
...
}
上記のインタフェースを満たすオブジェクトはすべて入力範囲と呼ばれ、繰り返し処理できる型です:
struct InputRange {
@property bool empty();
@property T front();
void popFront();
}
文字列と配列は範囲です
import std.stdio;
void main() {
auto s = "hello world";
auto a = [1, 2, 3, 4];
foreach (c; s) {
write(c, "!"); // h!e!l!l!o! !w!o!r!l!d!
}
writeln();
foreach (x; a) {
write(x * x, ", "); // 1, 4, 9, 16,
}
}
新しい入力範囲タイプを作成する
InputRangeコンセプトには、次の3つの関数があります。
struct InputRange(T) {
@property bool empty();
@property T front();
void popFront();
}
要するに、
- 範囲が空であるかどうかを確認する
- 現在の要素を取得する
- 次の要素に移動する
独自の型をInputRangeにするには、これら3つの関数を実装する必要があります。無限の四角形のシーケンスを見てみましょう。
struct SquaresRange {
int cur = 1;
@property bool empty() {
return false;
}
@property int front() {
return cur^^2;
}
void popFront() {
cur++;
}
}
フィボナッチの例については、 Dツアーをご覧ください。
Modified text is an extract of the original Stack Overflow Documentation
ライセンスを受けた CC BY-SA 3.0
所属していない Stack Overflow