跳轉到內容

面向型別程式設計/有界型別引數

來自華夏公益教科書

考慮以下程式碼

type Equatable {
  func equals(x Any) Bool
}

type Complex : Equatable {
  property real Float
  property imag Float

  func equals(x Any) Bool {
    if x is Complex then {
      var x = x as Complex
      return self.real == x.real & self.imag == x.imag
    }
    return false
  }
}

type Pair[T] {
  property first T
  property second T
}

main {
  var x = new Complex { real=2.0, imag=3.0 }
  var y = new Complex { real=2.0, imag=3.0 }
  return x.equals(y)
}

我們現在想為Pair實現equals方法

func equals(p Pair[T]) Bool {
  return self.first.equals(p.first) & self.second.equals(p.second)
}

但是請注意,這段程式碼無法編譯,因為編譯器無法確定T是否代表可比較型別。我們需要修改Pair的宣告為

type Pair[T:Equatable] { ... }

現在,可以確保T是可比較的,並且我們可以檢查對等的相等性

main {
  var x = new Complex { real=2.0, imag=3.0 }
  var y = new Complex { real=2.0, imag=4.0 }
  var p1 = new Pair[Complex] { first=x, second=y }
  var p2 = new Pair[Complex] { first=x, second=y }
  return p1.equals(p2)
}

這裡,T型別引數稱為有界的,因為對其施加了型別約束。

注意:可以使用 Funcy 應用程式嘗試此虛擬碼,該應用程式可以從Apple 的 App Store (iOS/macOS)Google Play (Android)Amazon Appstore免費下載。要執行的程式碼必須放在main {}塊中。

華夏公益教科書