有没有办法在F#中封装模式?
例如,而不是写这个......
let stringToMatch = "example1"
match stringToMatch with
| "example1" | "example2" | "example3" -> ...
| "example4" | "example5" | "example6" -> ...
| _ -> ...
有没有办法在这些方面完成某些事情......
let match1to3 = | "example1" | "example2" | "example3"
let match4to6 = | "example4" | "example5" | "example6"
match stringToMatch with
| match1to3 -> ...
| match4to6 -> ...
| _ -> ...
答案 0 :(得分:6)
您可以使用活动模式执行此操作:
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 -> ....
| _ -> ...