close
寫程式時,一定會遇到要使用 switch case 語法的時候,但這語法的缺點在於一次就只能設定一個變數,如果要一次使用多個變數判斷,就只能使用 else if 這個語法。但在 F#,則可以使用 Pattern Match 來解決。
現在用下列程式碼來示範如何使用 Pattern Match:
let y = 0 match y with | 1-> printfn "one" | 2-> printfn "two" | other -> printfn "other value" let bl = true match bl with | true -> printfn "It's true" | false -> printfn "It's false"
執行結果
上面的程式碼,只使用了一個條件,所以跟一般的 switch case 沒什麼差別。接下來的程式碼則是使用多個變數:
let income = false let age = false let country = false match income, age, country with | true, true, true -> printfn "Gold Member" | false, true, true -> printfn "Silver Member" | _-> printfn "you can't register"
執行結果
上面的程式碼用來判斷三個變數,是否符合會員資格,第一個條件是三個皆為 true,第二個則是 income 為 false,其餘皆為 true,如果條件皆不符合,程式則告知不能註冊會員。
當然,Pattern Match 好用的地方不僅於此,除了單純判斷變數,還可以加入其它的判斷邏輯,例如下列程式碼。
let income = 22000 let age = 18 let country = "Taiwan" match income, age, country with | _, _, "Taiwan" when income > 0 && age >= 18 -> printfn "Gold Member" | _ -> printfn "you can't register"
執行結果
要忽略變數的判斷,則用 _ 來表示,接在 when 關鍵字後面的,就是額外的判斷邏輯。個人認為這樣的功能,很適合用在需要判斷大量邏輯、規則的情況上。
全站熱搜
留言列表