2016-09-29 6 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

完璧!あなたは私の質問に答えただけでなく、アクティブパターンがちょうど私のためにクリックされました。ありがとう! – lambdakris

+3

ちょっとニックピッキングすると、**部分的なアクティブパターンの戻り値は 'Some()'になり、一致するのは 'MatchXtoY - > ...'になるはずです。 – Sehnsucht

+2

また、マッチャー'match text with'の代わりに' function'を使うことでもう少し簡潔になります。 –

関連する問題