diff --git a/Basic-practice-of-FSharp/Basic-practice-of-FSharp.fsproj b/Basic-practice-of-FSharp/Basic-practice-of-FSharp.fsproj index 8f859eb..dede8d8 100644 --- a/Basic-practice-of-FSharp/Basic-practice-of-FSharp.fsproj +++ b/Basic-practice-of-FSharp/Basic-practice-of-FSharp.fsproj @@ -18,6 +18,7 @@ - + + \ No newline at end of file diff --git a/Basic-practice-of-FSharp/OperatorOverloading.fs b/Basic-practice-of-FSharp/OperatorOverloading.fs new file mode 100644 index 0000000..0a1d5f4 --- /dev/null +++ b/Basic-practice-of-FSharp/OperatorOverloading.fs @@ -0,0 +1,46 @@ +module OperatorOverloading +// 运算符重载 + +// 运算符不过是一种特殊形态的函数 + +// 在类或者记录中重载运算符 +// static member (operator-symbols) (params) = body + +// 在全局作用域中存在运算符 +// let [inline] (operator-symbols) (params) = body + +// 请注意,在运算符重载中的运算符必须是静态的 + +type Point(x: int, y: int) = + member this.X = x + member this.Y = y + static member ( + ) (a: Point, b: Point) = Point(a.X + b.X, a.Y + b.Y) + override this.ToString() = $"X: {this.X}, Y: {this.Y}" + +let p1 = new Point(1, 3) +let p2 = new Point(2, 4) + +p1 + p2 |> printfn "%A" + +let ( - ) (a: Point) (b: Point) = Point(a.X - b.X, a.Y - b.Y) + +p1 - p2 |> printfn "%A" + +// 对于重载一元前缀运算符可使用~标记 +// let [inline] (~+) (value) = body + +// 创建新的运算符 +// 可从!$%&*+-./<=>?@^|~中进行组合,注意~仅作为一元运算符的标记,并不属于自定义运算符序列中 + +// 创建一个幂次运算符 +let inline ( ^ ) a b = a ** b // ** 本身就是pow,我们仅对其进行了重命名,实际上可以let ( ^ ) = ( ** ) + +2.0 ^ 4.0 |> printfn "%A" + +// 运算符是另一种形态的函数 +// 我们常见的|>运算符则是一个高阶函数, 将左侧表达式的至传递到右侧函数 +let inline ( |> ) p f = f p + +// 仅有一部分运算符可被作用于前缀运算符 + +