
- D 程式設計基礎
- D 程式設計 - 首頁
- D 程式設計 - 概述
- D 程式設計 - 環境
- D 程式設計 - 基本語法
- D 程式設計 - 變數
- D 程式設計 - 資料型別
- D 程式設計 - 列舉
- D 程式設計 - 字面量
- D 程式設計 - 運算子
- D 程式設計 - 迴圈
- D 程式設計 - 條件語句
- D 程式設計 - 函式
- D 程式設計 - 字元
- D 程式設計 - 字串
- D 程式設計 - 陣列
- D 程式設計 - 關聯陣列
- D 程式設計 - 指標
- D 程式設計 - 元組
- D 程式設計 - 結構體
- D 程式設計 - 聯合體
- D 程式設計 - 範圍
- D 程式設計 - 別名
- D 程式設計 - Mixin
- D 程式設計 - 模組
- D 程式設計 - 模板
- D 程式設計 - 不可變物件
- D 程式設計 - 檔案 I/O
- D 程式設計 - 併發
- D 程式設計 - 異常處理
- D 程式設計 - 契約
- D - 條件編譯
- D 程式設計 - 面向物件
- D 程式設計 - 類與物件
- D 程式設計 - 繼承
- D 程式設計 - 過載
- D 程式設計 - 封裝
- D 程式設計 - 介面
- D 程式設計 - 抽象類
- D 程式設計 - 有用資源
- D 程式設計 - 快速指南
- D 程式設計 - 有用資源
- D 程式設計 - 討論
D 程式設計 - 範圍
範圍是對元素訪問的抽象。這種抽象使得能夠在大量容器型別上使用大量演算法。範圍強調如何訪問容器元素,而不是容器如何實現。範圍是一個非常簡單的概念,它基於型別是否定義了某些成員函式集。
範圍是 D 的一個組成部分。D 的切片恰好是最強大的範圍 RandomAccessRange 的實現,Phobos 中有很多範圍特性。許多 Phobos 演算法返回臨時範圍物件。例如,在下面的程式碼中,filter() 選擇大於 10 的元素實際上返回的是一個範圍物件,而不是一個數組。
數字範圍
數字範圍非常常用,這些數字範圍的型別為 int。下面顯示了一些數字範圍的示例:
// Example 1 foreach (value; 3..7) // Example 2 int[] slice = array[5..10];
Phobos 範圍
與結構體和類介面相關的範圍是 Phobos 範圍。Phobos 是 D 語言編譯器附帶的官方執行時和標準庫。
有各種型別的範圍,包括:
- InputRange (輸入範圍)
- ForwardRange (前向範圍)
- BidirectionalRange (雙向範圍)
- RandomAccessRange (隨機訪問範圍)
- OutputRange (輸出範圍)
InputRange (輸入範圍)
最簡單的範圍是輸入範圍。其他範圍在其所基於的範圍之上增加了更多要求。InputRange 需要三個函式:
empty - 指定範圍是否為空;當範圍被認為為空時,它必須返回 true;否則返回 false。
front - 提供對範圍開頭元素的訪問。
popFront() - 透過移除第一個元素來縮短範圍的開頭。
示例
import std.stdio; import std.string; struct Student { string name; int number; string toString() const { return format("%s(%s)", name, number); } } struct School { Student[] students; } struct StudentRange { Student[] students; this(School school) { this.students = school.students; } @property bool empty() const { return students.length == 0; } @property ref Student front() { return students[0]; } void popFront() { students = students[1 .. $]; } } void main() { auto school = School([ Student("Raj", 1), Student("John", 2), Student("Ram", 3)]); auto range = StudentRange(school); writeln(range); writeln(school.students.length); writeln(range.front); range.popFront; writeln(range.empty); writeln(range); }
編譯並執行上述程式碼後,會產生以下結果:
[Raj(1), John(2), Ram(3)] 3 Raj(1) false [John(2), Ram(3)]
ForwardRange (前向範圍)
ForwardRange 另外還需要 InputRange 的其他三個函式中的 save 成員函式部分,並在呼叫 save 函式時返回範圍的副本。
import std.array; import std.stdio; import std.string; import std.range; struct FibonacciSeries { int first = 0; int second = 1; enum empty = false; // infinite range @property int front() const { return first; } void popFront() { int third = first + second; first = second; second = third; } @property FibonacciSeries save() const { return this; } } void report(T)(const dchar[] title, const ref T range) { writefln("%s: %s", title, range.take(5)); } void main() { auto range = FibonacciSeries(); report("Original range", range); range.popFrontN(2); report("After removing two elements", range); auto theCopy = range.save; report("The copy", theCopy); range.popFrontN(3); report("After removing three more elements", range); report("The copy", theCopy); }
編譯並執行上述程式碼後,會產生以下結果:
Original range: [0, 1, 1, 2, 3] After removing two elements: [1, 2, 3, 5, 8] The copy: [1, 2, 3, 5, 8] After removing three more elements: [5, 8, 13, 21, 34] The copy: [1, 2, 3, 5, 8]
BidirectionalRange (雙向範圍)
BidirectionalRange 在 ForwardRange 的成員函式之上另外提供了兩個成員函式。back 函式類似於 front,提供對範圍最後一個元素的訪問。popBack 函式類似於 popFront 函式,它從範圍中移除最後一個元素。
示例
import std.array; import std.stdio; import std.string; struct Reversed { int[] range; this(int[] range) { this.range = range; } @property bool empty() const { return range.empty; } @property int front() const { return range.back; // reverse } @property int back() const { return range.front; // reverse } void popFront() { range.popBack(); } void popBack() { range.popFront(); } } void main() { writeln(Reversed([ 1, 2, 3])); }
編譯並執行上述程式碼後,會產生以下結果:
[3, 2, 1]
無限 RandomAccessRange
與 ForwardRange 相比,另外還需要 opIndex()。此外,空函式的值在編譯時必須知道為 false。下面解釋了一個簡單的示例,其中使用了平方範圍。
import std.array; import std.stdio; import std.string; import std.range; import std.algorithm; class SquaresRange { int first; this(int first = 0) { this.first = first; } enum empty = false; @property int front() const { return opIndex(0); } void popFront() { ++first; } @property SquaresRange save() const { return new SquaresRange(first); } int opIndex(size_t index) const { /* This function operates at constant time */ immutable integerValue = first + cast(int)index; return integerValue * integerValue; } } bool are_lastTwoDigitsSame(int value) { /* Must have at least two digits */ if (value < 10) { return false; } /* Last two digits must be divisible by 11 */ immutable lastTwoDigits = value % 100; return (lastTwoDigits % 11) == 0; } void main() { auto squares = new SquaresRange(); writeln(squares[5]); writeln(squares[10]); squares.popFrontN(5); writeln(squares[0]); writeln(squares.take(50).filter!are_lastTwoDigitsSame); }
編譯並執行上述程式碼後,會產生以下結果:
25 100 25 [100, 144, 400, 900, 1444, 1600, 2500]
有限 RandomAccessRange
與雙向範圍相比,另外還需要 opIndex() 和 length。這將透過使用斐波那契數列和前面使用的平方範圍的詳細示例來解釋。此示例在普通的 D 編譯器上執行良好,但在線上編譯器上無法執行。
示例
import std.array; import std.stdio; import std.string; import std.range; import std.algorithm; struct FibonacciSeries { int first = 0; int second = 1; enum empty = false; // infinite range @property int front() const { return first; } void popFront() { int third = first + second; first = second; second = third; } @property FibonacciSeries save() const { return this; } } void report(T)(const dchar[] title, const ref T range) { writefln("%40s: %s", title, range.take(5)); } class SquaresRange { int first; this(int first = 0) { this.first = first; } enum empty = false; @property int front() const { return opIndex(0); } void popFront() { ++first; } @property SquaresRange save() const { return new SquaresRange(first); } int opIndex(size_t index) const { /* This function operates at constant time */ immutable integerValue = first + cast(int)index; return integerValue * integerValue; } } bool are_lastTwoDigitsSame(int value) { /* Must have at least two digits */ if (value < 10) { return false; } /* Last two digits must be divisible by 11 */ immutable lastTwoDigits = value % 100; return (lastTwoDigits % 11) == 0; } struct Together { const(int)[][] slices; this(const(int)[][] slices ...) { this.slices = slices.dup; clearFront(); clearBack(); } private void clearFront() { while (!slices.empty && slices.front.empty) { slices.popFront(); } } private void clearBack() { while (!slices.empty && slices.back.empty) { slices.popBack(); } } @property bool empty() const { return slices.empty; } @property int front() const { return slices.front.front; } void popFront() { slices.front.popFront(); clearFront(); } @property Together save() const { return Together(slices.dup); } @property int back() const { return slices.back.back; } void popBack() { slices.back.popBack(); clearBack(); } @property size_t length() const { return reduce!((a, b) => a + b.length)(size_t.init, slices); } int opIndex(size_t index) const { /* Save the index for the error message */ immutable originalIndex = index; foreach (slice; slices) { if (slice.length > index) { return slice[index]; } else { index -= slice.length; } } throw new Exception( format("Invalid index: %s (length: %s)", originalIndex, this.length)); } } void main() { auto range = Together(FibonacciSeries().take(10).array, [ 777, 888 ], (new SquaresRange()).take(5).array); writeln(range.save); }
編譯並執行上述程式碼後,會產生以下結果:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 777, 888, 0, 1, 4, 9, 16]
OutputRange (輸出範圍)
OutputRange 表示流式元素輸出,類似於將字元傳送到 stdout。OutputRange 需要支援 put(range, element) 操作。put() 是在 std.range 模組中定義的函式。它在編譯時確定範圍和元素的功能,並使用最合適的方法來輸出元素。下面顯示了一個簡單的示例。
import std.algorithm; import std.stdio; struct MultiFile { string delimiter; File[] files; this(string delimiter, string[] fileNames ...) { this.delimiter = delimiter; /* stdout is always included */ this.files ~= stdout; /* A File object for each file name */ foreach (fileName; fileNames) { this.files ~= File(fileName, "w"); } } void put(T)(T element) { foreach (file; files) { file.write(element, delimiter); } } } void main() { auto output = MultiFile("\n", "output_0", "output_1"); copy([ 1, 2, 3], output); copy([ "red", "blue", "green" ], output); }
編譯並執行上述程式碼後,會產生以下結果:
[1, 2, 3] ["red", "blue", "green"]