我仍然不明白为什么我会使用关键字inline
为函数使用关键字。
它给了我什么我还没有的东西?
let inline (|Positive|Neutral|Negative|) x =
match sign x with
| 1 -> Positive
| -1 -> Negative
| _ -> Neutral
我仍然不明白为什么我会使用关键字inline
为函数使用关键字。
它给了我什么我还没有的东西?
let inline (|Positive|Neutral|Negative|) x =
match sign x with
| 1 -> Positive
| -1 -> Negative
| _ -> Neutral
inline
在这种情况下,如果您尝试删除关键字,可能会更容易理解给您带来的好处:
let (|Positive|Neutral|Negative|) x =
match sign x with
| 1 -> Positive
| -1 -> Negative
| _ -> Neutral
此活动模式具有类型float -> Choice<unit,unit,unit>
。请注意,编译器已推断它仅适用于float
输入。
如果我们还定义了一个使用这种模式的函数,其后果可能最为明显,例如确定一个数字是否为自然数的函数:
let isNatural = function
| Positive -> true
| _ -> false
该函数的类型为float -> bool
,这意味着您只能将其用于float
输入:
> isNatural 1.;;
val it : bool = true
> isNatural 1;;
> isNatural 1;;
----------^
stdin(4,11): error FS0001: This expression was expected to have type
float
but here has type
int
如果您希望能够确定float
、int
、int64
等都是自然数怎么办?您是否应该为所有输入类型复制这些函数?
你不必。您可以inline
使用以下功能:
let inline (|Positive|Neutral|Negative|) x =
match sign x with
| 1 -> Positive
| -1 -> Negative
| _ -> Neutral
let inline isNatural x =
match x with
| Positive -> true
| _ -> false
由于inline
关键字,编译器保持函数的类型为泛型:
>
val inline ( |Positive|Neutral|Negative| ) :
x: ^a -> Choice<unit,unit,unit> when ^a : (member get_Sign : ^a -> int)
val inline isNatural : x: ^a -> bool when ^a : (member get_Sign : ^a -> int)
这意味着您可以使用任何类型作为输入,只要存在一个get_Sign
将该类型作为输入并返回的函数int
。
您现在可以使用 、 和其他数字类型调用float
函数int
:
> isNatural 1.;;
val it : bool = true
> isNatural 1;;
val it : bool = true