2016-09-29 47 views
5

F # içinde bir desen kapsülleme yolu var mı? onun yerine bu yazı ÖrneğinF # içinde bir desen kapsüllemek için bir yolu var mı?

...

let stringToMatch = "example1" 

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

bu satırlar boyunca bir şey başarmak için bazı yolu var mı

...

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

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

cevap

6

Active Patterns ile yapabilirsiniz:

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

Mükemmel! Sadece soruma cevap vermediniz, aynı zamanda Aktif Kalıplar benim için tıklanmıştı. Teşekkürler! – lambdakris

+3

küçük nitpicking, ilk kodu daha yakından eşleştirmek için ** Kısmi ** Aktif Modeller 'dönüşü' Bazı() 'olmalıdır ve eşleşme sadece" MatchXtoY -> ... "olmalıdır. – Sehnsucht

+2

Ayrıca, maççılar yapmış olabilir 'ile eşleştir' yerine 'işlevini kullanarak biraz daha fazla tersine çevir. –

İlgili konular