Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 -> ...
| _ -> ...
like image 747
lambdakris Avatar asked Sep 29 '16 21:09

lambdakris


1 Answers

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 -> ....
| _ -> ...
like image 85
Foole Avatar answered Oct 01 '22 02:10

Foole