【发布时间】:2016-09-19 17:17:59
【问题描述】:
F# 中一个非常方便的功能是您可以进行内联并保持一定程度的值类型多态性(尽管我认为“duck-typing”更合适):
// can be used with any argument that implements op_Explicit: ^a -> float
let inline Divide a b = float a / float b
但是当我将其扩展为包含在某种类型中时,F# 会推断出第一个参数是 float,即使我明确要求 转换为浮点数。我错过了什么,或者更好的是,我怎样才能恢复 op_Explicit 行为?我尝试添加静态成员约束,但这似乎没有帮助:
type XTest<'T> =
| Value of 'T
| Other of 'T
// a is inferred as float, b as req. op_Explicit
static member inline Divide a b =
match a with
| Value x ->
match b with
| Value y ->
let res = float x / float y
XTest.Value res |> Some
| _ -> failwith "not implemented"
| Other x-> Some (XTest.Other x)
也许需要注意:如果我删除 Other 可区分联合,它会正确推断第一个参数的类型,因为 “需要成员 op_Explicit”
【问题讨论】:
标签: generics f# constraints type-inference