Fsharp-operator-overloading

提供:Dev Guides
移動先:案内検索

F#-オペレーターのオーバーロード

F#で使用可能な組み込み演算子のほとんどを再定義またはオーバーロードできます。 したがって、プログラマはユーザー定義型の演算子も使用できます。

演算子は、括弧で囲まれた特別な名前の関数です。 静的クラスメンバーとして定義する必要があります。 他の関数と同様に、オーバーロードされた演算子には戻り値の型とパラメーターリストがあります。

次の例は、+を示しています。複素数の演算子-

//overloading + operator
static member (+) (a : Complex, b: Complex) =
Complex(a.x + b.x, a.y + b.y)

上記の関数は、ユーザー定義クラスComplexの加算演算子(+)を実装します。 2つのオブジェクトの属性を追加し、結果のComplexオブジェクトを返します。

オペレーターのオーバーロードの実装

次のプログラムは、完全な実装を示しています-

//implementing a complex class with +, and - operators
//overloaded
type Complex(x: float, y : float) =
   member this.x = x
   member this.y = y
  //overloading + operator
   static member (+) (a : Complex, b: Complex) =
      Complex(a.x + b.x, a.y + b.y)

  //overloading - operator
   static member (-) (a : Complex, b: Complex) =
      Complex(a.x - b.x, a.y - b.y)

  //overriding the ToString method
   override this.ToString() =
      this.x.ToString() + " " + this.y.ToString()

//Creating two complex numbers
let c1 = Complex(7.0, 5.0)
let c2 = Complex(4.2, 3.1)

//addition and subtraction using the
//overloaded operators
let c3 = c1 + c2
let c4 = c1 - c2

//printing the complex numbers
printfn "%s" (c1.ToString())
printfn "%s" (c2.ToString())
printfn "%s" (c3.ToString())
printfn "%s" (c4.ToString())

あなたがプログラムをコンパイルして実行すると、次の出力が得られます-

7 5
4.2 3.1
11.2 8.1
2.8 1.9