📅  最后修改于: 2021-01-01 04:43:02             🧑  作者: Mango
F#提供模式匹配以逻辑上匹配数据。它类似于C,C++编程语言中使用的else if和switch情况。我们可以将模式匹配应用于caonstant值,对象,列表,记录等。
您可以在模式匹配中使用常量值,如以下示例所示。
let patternMatch a =
match a with
| 1 -> "You entered 1"
| 2 -> "You entered 2"
| _ -> "You entered something other then 1 or 2"
printf "%s" (patternMatch 2)
输出:
You entered 2
您可以使用模式中的对象搜索输入的最佳匹配。
let objectPatternMatch (a:obj) =
match a with
| :? int -> "You entered integer value"
| :? float -> "You entered float value"
| _ -> "You entered something other than integer or float"
printfn "%s" (objectPatternMatch 10)
输出:
You entered integer value
以下程序显示了如何使用条件模式匹配。
let conditionalPatternMatching x y =
match (x,y) with
| (x,y) when x>y -> printfn "X is greater than y"
| (x,y) when x printfn "Y is greater than x"
| _ -> printf "X = Y"
conditionalPatternMatching 20 10
输出:
X is greater than y
在F#中,您可以在列表中应用模式匹配。让我们来看一个例子。
let listPatternMatching list =
match list with
| [var] -> var
| [var1;var2]-> var1+var2
printf "%d" (listPatternMatching [2;1])
输出:
3
您也可以在元组中使用模式匹配。让我们来看一个例子。
let tuplePatternMatching tuple =
match tuple with
| (0, 0) -> printfn "Both values zero."
| (0, var2) -> printfn "First value is 0 in (0, %d)" var2
| (var1, 0) -> printfn "Second value is 0 in (%d, 0)" var1
| _ -> printfn "Both nonzero."
tuplePatternMatching (0, 1)
输出:
First value is 0 in (0, 1)