我正在尝试编写自定义DivideByInt,如下所示
type Pair = Pair of int * int with
static member DivideByInt pair int = pair
[<EntryPoint>]
let main argv =
LanguagePrimitives.DivideByInt (Pair(1,2)) 1
|> ignore
0
// compiler error: "FS0001: Method or object constructor 'DivideByInt' not found"
为什么编译器找不到Pair.DivideByInt?
答案 0 :(得分:6)
Pair.DivideByInt
必须将元组作为输入
更正后的版本:
type Pair = Pair of int * int with
static member DivideByInt (pair, int) = pair
答案 1 :(得分:1)
类型int
不是一个好的起点,因为它不支持DivideByInt
,但你可以使类型通用:
type Pair<'t> = Pair of 't * 't with
static member inline DivideByInt (Pair (x, y), i:int) =
Pair (LanguagePrimitives.DivideByInt x i, LanguagePrimitives.DivideByInt y i)
[<EntryPoint>]
let main argv =
LanguagePrimitives.DivideByInt (Pair (1.0, 2.0)) 1 |> ignore
LanguagePrimitives.DivideByInt (Pair (1m , 2m )) 1 |> ignore
0
否则你可以“强制”它在一对int上工作并保持通用:
type Pair<'t> = Pair of 't * 't with
static member inline DivideByInt (Pair (x, y), i:int) =
Pair (LanguagePrimitives.DivideByInt x i, LanguagePrimitives.DivideByInt y i)
static member DivideByInt (Pair (x:int, y:int), i:int) =
Pair (x / i, y / i)
static member DivideByInt (Pair (x:uint32, y:uint32), i:int) =
Pair (x / uint32 i, y / uint32 i)
答案 2 :(得分:-1)
这对我有用:
LanguagePrimitives.DivideByInt 3.0 4
|> printfn "%A"
所以它没有得到元组,但有两个论点。以上给出结果:0.75