pho*_*oog 5 f# pattern-matching
在https://docs.microsoft.com/zh-cn/dotnet/fsharp/language-reference/pattern-matching#tuple-pattern处,有一个带有类型注释的模式示例:
模式可以具有类型注释。它们的行为类似于其他类型注释,并像其他类型注释一样指导推理。模式中的类型注释必须带括号。以下代码显示了具有类型注释的模式。
Run Code Online (Sandbox Code Playgroud)let detect1 x = match x with | 1 -> printfn "Found a 1!" | (var1 : int) -> printfn "%d" var1 detect1 0 detect1 1
类型注释(var1 : int)是多余的,因为1前一个模式中的文字会明确地建立类型。
在任何情况下,诸如此类的类型注释会很有用吗?
实际上,即使您在函数参数中使用类型注释,您也在模式中使用类型注释。F# 模式匹配甚至适用于函数参数(let通常是绑定)。
因此,像往常一样,当我们想要立即强制执行类型而不是依赖类型推断时,类型注释非常有用。我们可以在很多地方放置类型注释来达到相同的结果。只需选择最适合情况的地方即可。考虑下面的例子:
let detect2 (x : int option) =
match x with
| Some y -> ...
| None -> ...
Run Code Online (Sandbox Code Playgroud)
我们可以写得更短:
let detect2 x =
match x with
| Some (y : int)
| None -> ...
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我们应该选择后者。