运算符重载
This commit is contained in:
parent
38c49a703f
commit
3f6df1c942
|
@ -19,5 +19,6 @@
|
|||
<Compile Include="PatternMatching.fs" />
|
||||
<Compile Include="ComputationExpressions.fs" />
|
||||
<Compile Include="ExceptionThrowing.fs" />
|
||||
<Compile Include="OperatorOverloading.fs" />
|
||||
</ItemGroup>
|
||||
</Project>
|
|
@ -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
|
||||
|
||||
// 仅有一部分运算符可被作用于前缀运算符
|
||||
|
||||
|
Loading…
Reference in New Issue