有没有办法在F#中封装模式?

lam*_*ris 5 f#

有没有办法在F#中封装模式?

例如,而不是写这个......

let stringToMatch = "example1"

match stringToMatch with
| "example1" | "example2" | "example3" -> ...
| "example4" | "example5" | "example6" -> ...
| _ -> ...
Run Code Online (Sandbox Code Playgroud)

有没有办法在这些方面完成某些事情......

let match1to3 = | "example1" | "example2" | "example3"
let match4to6 = | "example4" | "example5" | "example6"

match stringToMatch with
| match1to3 -> ...
| match4to6 -> ...
| _ -> ...
Run Code Online (Sandbox Code Playgroud)

Foo*_*ole 6

您可以使用Active Patterns执行此操作:

let (|Match1to3|_|) text = 
    match text with
    | "example1" | "example2" | "example3" -> Some text
    | _ -> None

let (|Match4to6|_|) text = 
    match text with
    | "example4" | "example5" | "example6" -> Some text
    | _ -> None

match stringToMatch with
| Match1to3 text -> ....
| Match4to6 text -> ....
| _ -> ...
Run Code Online (Sandbox Code Playgroud)

  • 小挑剔,为了更接近地匹配初始代码**部分**活动模式的返回应该是`Some()`并且匹配应该只是`MatchXtoY - > ...` (3认同)
  • 完善!你不仅回答了我的问题,而且只为我点击了Active Patterns.谢谢! (2认同)
  • 此外,通过使用`function`而不是`match text with`,本可以使匹配器变得更加简洁. (2认同)