運算子多載

本主題說明如何在類別或記錄類型,及全域層級多載算術運算子。

語法

// Overloading an operator as a class or record member.
static member (operator-symbols) (parameter-list) =
    method-body
// Overloading an operator at the global level
let [inline] (operator-symbols) parameter-list = function-body

備註

在之前的語法中,運算子符號+-*/= 等其中一個。 參數清單會依運算元出現在該運算子一般語法的順序,指定運算元。 方法主體會建構產生值。

運算子的運算子多載必須是靜態。 一元運算子的運算子多載,例如 +- ,必須使用運算子符號的波狀符號 (~),指出運算子是一元運算子,而不是二元運算子,如下列宣告所示。

static member (~-) (v : Vector)

下列程式碼說明只有兩個運算子的向量類別,一個運算子用於一元減號運算,一個運算子用於純量乘法。 在此範例中,您需要兩個純量乘法的多載,因為無論向量和純量出現的順序為何,運算子都必須可用。

type Vector(x: float, y : float) =
   member this.x = x
   member this.y = y
   static member (~-) (v : Vector) =
     Vector(-1.0 * v.x, -1.0 * v.y)
   static member (*) (v : Vector, a) =
     Vector(a * v.x, a * v.y)
   static member (*) (a, v: Vector) =
     Vector(a * v.x, a * v.y)
   override this.ToString() =
     this.x.ToString() + " " + this.y.ToString()

let v1 = Vector(1.0, 2.0)

let v2 = v1 * 2.0
let v3 = 2.0 * v1

let v4 = - v2

printfn "%s" (v1.ToString())
printfn "%s" (v2.ToString())
printfn "%s" (v3.ToString())
printfn "%s" (v4.ToString())

建立新的運算子

您可以多載所有標準運算子,但您也可以從特定字元序列建立新的運算子。 允許的運算子字元為 !$%&*+-./<=>?@^|~~ 字元有將運算子設為一元的特殊意義,而不是運算子字元序列的一部分。 不是所有運算子都可設為一元。

根據您使用的確切字元序列,運算子會有特定的優先順序和關聯性。 關聯性可以由左至右或由右至左,並用於序列中相同優先順序層級的運算子,而不需要括弧。

運算子字元 . 不會影響優先順序,所以如果您要定義自己的乘法版本,且優先順序和關聯性與一般乘法相同時,您可以建立運算子,例如 .*

$ 運算子必須獨立且不含其他符號。

您可以在符號和運算子參考中,找到顯示 F# 中所有運算子優先順序的資料表。

多載運算子名稱

編譯運算子運算式時,F# 編譯器會產生方法,針對該運算子使用編譯器產生的名稱。 這是在方法的通用中間語言 (CIL),及反映和 IntelliSense 中出現的名稱。 在 F# 程式碼中通常不必使用這些名稱。

下表顯示標準運算子與對應的產生名稱。

運算子 產生的名稱
[] op_Nil
:: op_Cons
+ op_Addition
- op_Subtraction
* op_Multiply
/ op_Division
@ op_Append
^ op_Concatenate
% op_Modulus
&&& op_BitwiseAnd
||| op_BitwiseOr
^^^ op_ExclusiveOr
<<< op_LeftShift
~~~ op_LogicalNot
>>> op_RightShift
~+ op_UnaryPlus
~- op_UnaryNegation
= op_Equality
<= op_LessThanOrEqual
>= op_GreaterThanOrEqual
< op_LessThan
> op_GreaterThan
? op_Dynamic
?<- op_DynamicAssignment
|> op_PipeRight
<| op_PipeLeft
! op_Dereference
>> op_ComposeRight
<< op_ComposeLeft
<@ @> op_Quotation
<@@ @@> op_QuotationUntyped
+= op_AdditionAssignment
-= op_SubtractionAssignment
*= op_MultiplyAssignment
/= op_DivisionAssignment
.. op_Range
.. .. op_RangeStep

請注意,F# 中的 not 運算子不會發出 op_Inequality,因為此運算子不是符號運算子。 此運算子是函式會發出 IL 並否定布林運算式。

這裡未列出的其他運算子字元組合可作為運算子,並使用下表個別字元串連的名稱。 例如,+! 會變成 op_PlusBang

運算子字元 名稱
> Greater
< Less
+ Plus
- Minus
* Multiply
/ Divide
= Equals
~ Twiddle
$ Dollar
% Percent
. Dot
& Amp
| Bar
@ At
^ Hat
! Bang
? Qmark
( LParen
, Comma
) RParen
[ LBrack
] RBrack

前置和中置運算子

前置運算子應放置在運算元前面,如同函式。 中置運算子應放置在兩個運算元之間。

只有特定運算子可以作為前置詞運算子使用。 部分運算子一律是前置詞運算子,其他運算子可以是 中置或前置,其餘運算子一律是中置運算子。 開頭為 ! 的運算子 (不包括 !=) 以及 ~ 運算子或 ~ 的重複序列一律為前置運算子。 運算子 +-+.-.&&&%%% 可以是前置運算子或中置運算子。 定義前置運算子時,您可以在前置運算子的開頭新增 ~,區分前置版本與中置版本的運算子。 只有定義運算子,而不是使用運算子時,才使用 ~

範例

下列程式碼說明如何使用運算子多載實作分數類型。 分數是以分子和分母表示。 函式 hcf 用來判斷最大公因數,即用來約分。

// Determine the highest common factor between
// two positive integers, a helper for reducing
// fractions.
let rec hcf a b =
  if a = 0u then b
  elif a<b then hcf a (b - a)
  else hcf (a - b) b

// type Fraction: represents a positive fraction
// (positive rational number).
type Fraction =
   {
      // n: Numerator of fraction.
      n : uint32
      // d: Denominator of fraction.
      d : uint32
   }

   // Produce a string representation. If the
   // denominator is "1", do not display it.
   override this.ToString() =
      if (this.d = 1u)
        then this.n.ToString()
        else this.n.ToString() + "/" + this.d.ToString()

   // Add two fractions.
   static member (+) (f1 : Fraction, f2 : Fraction) =
      let nTemp = f1.n * f2.d + f2.n * f1.d
      let dTemp = f1.d * f2.d
      let hcfTemp = hcf nTemp dTemp
      { n = nTemp / hcfTemp; d = dTemp / hcfTemp }

   // Adds a fraction and a positive integer.
   static member (+) (f1: Fraction, i : uint32) =
      let nTemp = f1.n + i * f1.d
      let dTemp = f1.d
      let hcfTemp = hcf nTemp dTemp
      { n = nTemp / hcfTemp; d = dTemp / hcfTemp }

   // Adds a positive integer and a fraction.
   static member (+) (i : uint32, f2: Fraction) =
      let nTemp = f2.n + i * f2.d
      let dTemp = f2.d
      let hcfTemp = hcf nTemp dTemp
      { n = nTemp / hcfTemp; d = dTemp / hcfTemp }

   // Subtract one fraction from another.
   static member (-) (f1 : Fraction, f2 : Fraction) =
      if (f2.n * f1.d > f1.n * f2.d)
        then failwith "This operation results in a negative number, which is not supported."
      let nTemp = f1.n * f2.d - f2.n * f1.d
      let dTemp = f1.d * f2.d
      let hcfTemp = hcf nTemp dTemp
      { n = nTemp / hcfTemp; d = dTemp / hcfTemp }

   // Multiply two fractions.
   static member (*) (f1 : Fraction, f2 : Fraction) =
      let nTemp = f1.n * f2.n
      let dTemp = f1.d * f2.d
      let hcfTemp = hcf nTemp dTemp
      { n = nTemp / hcfTemp; d = dTemp / hcfTemp }

   // Divide two fractions.
   static member (/) (f1 : Fraction, f2 : Fraction) =
      let nTemp = f1.n * f2.d
      let dTemp = f2.n * f1.d
      let hcfTemp = hcf nTemp dTemp
      { n = nTemp / hcfTemp; d = dTemp / hcfTemp }

   // A full set of operators can be quite lengthy. For example,
   // consider operators that support other integral data types,
   // with fractions, on the left side and the right side for each.
   // Also consider implementing unary operators.

let fraction1 = { n = 3u; d = 4u }
let fraction2 = { n = 1u; d = 2u }
let result1 = fraction1 + fraction2
let result2 = fraction1 - fraction2
let result3 = fraction1 * fraction2
let result4 = fraction1 / fraction2
let result5 = fraction1 + 1u
printfn "%s + %s = %s" (fraction1.ToString()) (fraction2.ToString()) (result1.ToString())
printfn "%s - %s = %s" (fraction1.ToString()) (fraction2.ToString()) (result2.ToString())
printfn "%s * %s = %s" (fraction1.ToString()) (fraction2.ToString()) (result3.ToString())
printfn "%s / %s = %s" (fraction1.ToString()) (fraction2.ToString()) (result4.ToString())
printfn "%s + 1 = %s" (fraction1.ToString()) (result5.ToString())

輸出:

3/4 + 1/2 = 5/4
3/4 - 1/2 = 1/4
3/4 * 1/2 = 3/8
3/4 / 1/2 = 3/2
3/4 + 1 = 7/4

全域層級的運算子

您也可以在全域層級定義運算子。 下列程式碼會定義運算子 +?

let inline (+?) (x: int) (y: int) = x + 2*y
printf "%d" (10 +? 1)

上述程式碼的輸出是 12

您可以透過此方式重新定義一般算術運算子,因為 F# 的範圍規則指定新定義的運算子的優先順序高於內建運算子。

關鍵字 inline 常搭配全域運算子使用且通常是小型函式,最適合與呼叫程式碼整合。 內置運算子函式也可讓運算子函式使用靜態解析的型別參數,產生靜態解析的泛型程式碼。 如需詳細資訊,請參閱內置函式靜態解析的型別參數

另請參閱