简体   繁体   中英

Is there a way to encapsulate a pattern in F#?

Is there a way to encapsulate a pattern in F#?

For example, instead of writing this...

let stringToMatch = "example1"

match stringToMatch with
| "example1" | "example2" | "example3" -> ...
| "example4" | "example5" | "example6" -> ...
| _ -> ...

Is there some way to accomplish something along these lines...

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

match stringToMatch with
| match1to3 -> ...
| match4to6 -> ...
| _ -> ...

You can do this with 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 -> ....
| _ -> ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM