From 12cce6d8b4e3842e2bd446527fd56fbcedb1a975 Mon Sep 17 00:00:00 2001 From: Sanchime Date: Sat, 26 Feb 2022 13:51:01 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Basic-practice-of-FSharp/PatternMatching.fs | 51 +++++++++++++++++++-- 1 file changed, 48 insertions(+), 3 deletions(-) diff --git a/Basic-practice-of-FSharp/PatternMatching.fs b/Basic-practice-of-FSharp/PatternMatching.fs index cd28713..be3fef3 100644 --- a/Basic-practice-of-FSharp/PatternMatching.fs +++ b/Basic-practice-of-FSharp/PatternMatching.fs @@ -10,6 +10,8 @@ match 1 with | 3 -> printfn "数字3" | _ -> printfn "其他数字" +// 通配符模式用下划线表示,并匹配任意输入 + // 匹配字符串 match "one" with | "one" -> printfn "字符串one" @@ -18,16 +20,59 @@ match "one" with type Shape = Square | Circular -// 匹配可区分联合 +// 可区分联合模式 +// 可分解可区分联合成员 match Square with -| Square -> printfn"匹配Square" -| Circular -> printfn"匹配Circular" +| Square -> printfn "匹配Square" +| Circular -> printfn "匹配Circular" + +// 记录模式 +// 可分解记录成员 +type UserInfo = { Name: string; Email: string } +let user = { Name = "小明"; Email = "xxx@xxx.com" } +match user with +| { Name = name; Email = email } as user when name = "小明" -> printfn "%A" user +| _ -> printfn "%A" user // 或模式 match 1 with | 1 | 2 | 3 -> printfn "1或2或3" | _ -> printfn"其他" +// 列表模式 + +match [1] with +| [] -> printfn "没有元素" +| [_] -> printfn "一个元素" +| [_; _] -> printfn "两个元素" +| _ -> printfn "其他" + +// 数组模式 +match [|1; 2|] with +| [||] -> printfn "没有元素" +| [|_|] -> printfn "一个元素" +| [|_; _|] -> printfn "两个元素" +| _ -> printfn "其他" + +// 元组模式 +match (0, 1) with +| (0, 0) -> printfn "(0, 0)" +| (0, 1) -> printfn "(0, 1)" +| _ -> printfn "其他" + +// as模式 +match "111" with +| "111" as s -> printfn "字符串:%s" s +| _ -> printfn "其他" + +// 可以在模式匹配中写条件 +// 变量模式 + 条件 +match 5 with +| n when n < 2 -> printfn "%d小于2" n +| n when n < 6 -> printfn "%d小于6" n +| n -> printfn "%d不满足上述匹配" n + + // cons模式 let rec sum_of_list list = match list with