模式匹配
This commit is contained in:
parent
6665adb75b
commit
80614a0a3b
|
@ -15,5 +15,6 @@
|
|||
<Compile Include="CurryingFunction.fs" />
|
||||
<Compile Include="Loop.fs" />
|
||||
<Compile Include="TypeCreating.fs" />
|
||||
<Compile Include="PatternMatching.fs" />
|
||||
</ItemGroup>
|
||||
</Project>
|
|
@ -0,0 +1,49 @@
|
|||
module PatternMatching
|
||||
|
||||
|
||||
// match value_to_match with | patterns
|
||||
|
||||
// 匹配数字
|
||||
match 1 with
|
||||
| 1 -> printfn "数字1"
|
||||
| 2 -> printfn "数字2"
|
||||
| 3 -> printfn "数字3"
|
||||
| _ -> printfn "其他数字"
|
||||
|
||||
// 匹配字符串
|
||||
match "one" with
|
||||
| "one" -> printfn "字符串one"
|
||||
| "two" -> printfn "字符串two"
|
||||
| _ -> printfn "其他字符串"
|
||||
|
||||
type Shape = Square | Circular
|
||||
|
||||
// 匹配可区分联合
|
||||
match Square with
|
||||
| Square -> printfn"匹配Square"
|
||||
| Circular -> printfn"匹配Circular"
|
||||
|
||||
// 或模式
|
||||
match 1 with
|
||||
| 1 | 2 | 3 -> printfn "1或2或3"
|
||||
| _ -> printfn"其他"
|
||||
|
||||
// cons模式
|
||||
let rec sum_of_list list =
|
||||
match list with
|
||||
| [] -> 0
|
||||
| [x] -> x
|
||||
| x::xs -> x + sum_of_list xs
|
||||
|
||||
[] |> sum_of_list |> printfn "%A"
|
||||
[1] |> sum_of_list |> printfn "%A"
|
||||
[1; 2; 3] |> sum_of_list |> printfn"%A"
|
||||
|
||||
// function构建一个函数,并且省略一个参数进行模式匹配
|
||||
|
||||
1
|
||||
|> function
|
||||
| 1 -> printfn "数字1"
|
||||
| 2 -> printfn "数字2"
|
||||
| 3 -> printfn "数字3"
|
||||
| _ -> printfn "其他数字"
|
Loading…
Reference in New Issue