运算符重载

This commit is contained in:
Sanchime 2022-03-19 20:59:37 +08:00
parent 38c49a703f
commit 3f6df1c942
2 changed files with 48 additions and 1 deletions

View File

@ -18,6 +18,7 @@
<Compile Include="TypeCreating.fs" /> <Compile Include="TypeCreating.fs" />
<Compile Include="PatternMatching.fs" /> <Compile Include="PatternMatching.fs" />
<Compile Include="ComputationExpressions.fs" /> <Compile Include="ComputationExpressions.fs" />
<Compile Include="ExceptionThrowing.fs"/> <Compile Include="ExceptionThrowing.fs" />
<Compile Include="OperatorOverloading.fs" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -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
//