F#转换为文本运行时提供的类型

sti*_*ing 2 f# type-conversion

换句话说,如果我想要一个完全通用的函数,我如何确保数值类型之间的编译/运行时转换.

例如:

let f x = x + 1 // int -> int
Run Code Online (Sandbox Code Playgroud)

自动假定int因为1.

我目前的黑客攻击是:

let gettype (x:'T) = typeof<'T>  // 'T -> Type
let one x = Convert.ChangeType (1, (gettype x))  // 'a -> obj
let f x = x + one(x) // obj -> obj
Run Code Online (Sandbox Code Playgroud)

但这不起作用,因为+没有为objs 定义

Fyo*_*kin 6

如果你想要一个完全通用的函数,为参数添加一个,我建议你使用LanguagePrimitives.GenericOne:

let inline f x = x + LanguagePrimitives.GenericOne
Run Code Online (Sandbox Code Playgroud)

请注意,您还需要内联函数,因为否则运算符(+)不能是通用的.