活動模式作為 .NET API 包裝器
Active Patterns 可用於呼叫某些 .NET API 感覺更自然,特別是那些使用輸出引數返回的不僅僅是函式返回值。
例如,你通常按如下方式呼叫 System.Int32.TryParse
方法:
let couldParse, parsedInt = System.Int32.TryParse("1")
if couldParse then printfn "Successfully parsed int: %i" parsedInt
else printfn "Could not parse int"
你可以使用模式匹配來改善這一點:
match System.Int32.TryParse("1") with
| (true, parsedInt) -> printfn "Successfully parsed int: %i" parsedInt
| (false, _) -> printfn "Could not parse int"
但是,我們還可以定義包含 System.Int32.TryParse
函式的以下活動模式:
let (|Int|_|) str =
match System.Int32.TryParse(str) with
| (true, parsedInt) -> Some parsedInt
| _ -> None
現在我們可以做到以下幾點:
match "1" with
| Int parsedInt -> printfn "Successfully parsed int: %i" parsedInt
| _ -> printfn "Could not parse int"
包含在活動模式中的另一個好選擇是正規表示式 API:
let (|MatchRegex|_|) pattern input =
let m = System.Text.RegularExpressions.Regex.Match(input, pattern)
if m.Success then Some m.Groups.[1].Value
else None
match "bad" with
| MatchRegex "(good|great)" mood ->
printfn "Wow, it's a %s day!" mood
| MatchRegex "(bad|terrible)" mood ->
printfn "Unfortunately, it's a %s day." mood
| _ ->
printfn "Just a normal day"