This commit is contained in:
parent
80614a0a3b
commit
12cce6d8b4
|
@ -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
|
||||
|
|
Loading…
Reference in New Issue