当前位置 : 主页 > 手机开发 > 其它 >

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

来源:互联网 收集:自由互联 发布时间:2021-06-19
有没有办法在F#中封装模式? 例如,而不是写这个…… let stringToMatch = "example1"match stringToMatch with| "example1" | "example2" | "example3" - ...| "example4" | "example5" | "example6" - ...| _ - ... 有没有办法在这
有没有办法在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 -> ...
| _ -> ...
您可以使用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 -> ....
| _ -> ...
网友评论