2016-09-29 37 views
5

有没有办法在F#中封装一个模式?有没有办法在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 -> ... 
| _ -> ... 

回答

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 -> .... 
| _ -> ... 
+2

完美!你不仅回答了我的问题,而且还为我点击了Active Patterns。谢谢! – lambdakris

+3

有点挑剔,为了匹配最初的代码更加接近**部分**活动模式的返回应该是'Some()',匹配应该只是'MatchXtoY - > ...' – Sehnsucht

+2

另外,可以使匹配器通过使用'function'而不是''将文本与''匹配。 –

相关问题