在这种情况下,如果您尝试删除关键字,可能更容易理解inline 为您提供的内容:
let (|Positive|Neutral|Negative|) x =
match sign x with
| 1 -> Positive
| -1 -> Negative
| _ -> Neutral
此活动模式的类型为 float -> Choice<unit,unit,unit>。请注意,编译器已推断它仅适用于 float 输入。
如果我们还定义了一个使用这种模式的函数,其后果可能最为明显,例如确定一个数字是否为natural number:
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)
这意味着您可以使用 any 类型作为输入,只要存在一个函数 get_Sign 将该类型作为输入并返回 int。
您现在可以使用float、int 和其他数字类型调用函数:
> isNatural 1.;;
val it : bool = true
> isNatural 1;;
val it : bool = true