为什么" _"用于活动模式?

时间:2017-06-25 00:08:33

标签: f#

从这link我看到他们使用" _"在活跃的模式。

 let (|Int|_|) str =
     match System.Int32.TryParse(str) with
     | (true,int) -> Some(int)
     | _ -> None

当我查看来自其他link的示例时,我不会看到下划线。

 let (|Even|Odd|) input = if input % 2 = 0 then Even else Odd

这两种实现有什么区别?

1 个答案:

答案 0 :(得分:4)

这是写在this doc page上的 (|Int|_|) str =...是部分活动模式。 let (|Even|Odd|) input =...是活动模式。见下文。

// From doc link
module ActivePatternSample =
  let (|Even|Odd|) input = if input % 2 = 0 then Even else Odd 

  let TestNumber input =
    match input with
    | Even -> printfn "%d is even" input
    | Odd -> printfn "%d is odd" input

// Rewrite to partial Active Pattern
module PartialActivePatternSample =
  let (|Even|_|) input =
    match (input%2) with
    | 0 -> Some input
    | _ -> None

  let (|Odd|_|) input =
    match input%2 with
    | 1 -> Some input
    | _ -> None

  let TestNumber input =
    match input with
    | Even input -> printfn "%A is even" input
    | Odd input -> printfn "%A is odd" input
    | _ -> printfn "can not come here"