使用内联的 F#:仍然无法为泛型函数匹配不同类型
F# using inline: still fail to match different type for generic function
我尝试使用 "inline" 定义适合不同输入参数类型的函数:
> let x=2.0
- let inline f x=x+1
- f x;;
f x;;
--^
stdin(6,3): error FS0001: This expression was expected to have type
int
but here has type
float
我希望在对 f 应用 "inline" 之后,我得到了一个通用函数调用 "f"。但似乎失败了。
如何纠正?
那是因为您要在函数中添加 1
。因此 x
必须是 int
.
如果您提供 +
的两边作为参数,inline
将起作用:
> let inline f x y = x + y;;
val inline f :
x: ^a -> y: ^b -> ^c
when ( ^a or ^b) : (static member ( + ) : ^a * ^b -> ^c)
如您所见,它的类型被解析为 具有 +
的任何类型。您可以使用它来将两个 int
sor two
float`s 相加:
> f 1 2;;
val it : int = 3
> f 1. 2.;;
val it : float = 3.0
但是您不能使用它来将 int
添加到 float
:
> f 1. 2;;
f 1. 2;;
-----^
stdin(9,6): error FS0001: The type 'int' does not match the type 'float'
最好的方法是像这样使用 genericOne
:
let inline f x = x + LanguagePrimitives.GenericOne
这是因为当您使用 1
时,编译器推断函数参数必须是 int
,因为您只能将 ints
添加到其他 ints
然后你可以用
调用它
> f 1;;
val it : int = 2
> f 1.0;;
val it : float = 2.0
我尝试使用 "inline" 定义适合不同输入参数类型的函数:
> let x=2.0
- let inline f x=x+1
- f x;;
f x;;
--^
stdin(6,3): error FS0001: This expression was expected to have type
int
but here has type
float
我希望在对 f 应用 "inline" 之后,我得到了一个通用函数调用 "f"。但似乎失败了。 如何纠正?
那是因为您要在函数中添加 1
。因此 x
必须是 int
.
+
的两边作为参数,inline
将起作用:
> let inline f x y = x + y;;
val inline f :
x: ^a -> y: ^b -> ^c
when ( ^a or ^b) : (static member ( + ) : ^a * ^b -> ^c)
如您所见,它的类型被解析为 具有 +
的任何类型。您可以使用它来将两个 int
sor two
float`s 相加:
> f 1 2;;
val it : int = 3
> f 1. 2.;;
val it : float = 3.0
但是您不能使用它来将 int
添加到 float
:
> f 1. 2;;
f 1. 2;;
-----^
stdin(9,6): error FS0001: The type 'int' does not match the type 'float'
最好的方法是像这样使用 genericOne
:
let inline f x = x + LanguagePrimitives.GenericOne
这是因为当您使用 1
时,编译器推断函数参数必须是 int
,因为您只能将 ints
添加到其他 ints
然后你可以用
调用它> f 1;;
val it : int = 2
> f 1.0;;
val it : float = 2.0