本文概述
F#提供模式匹配以逻辑上匹配数据。它类似于C, C ++编程语言中使用的else if和switch嵌套案例。我们可以将模式匹配应用于caonstant值, 对象, 列表, 记录等。
常量值的F#模式匹配示例
你可以在模式匹配中使用常量值, 如以下示例所示。
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
使用对象示例进行F#模式匹配
你可以使用模式中的对象来搜索输入的最佳匹配。
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
F#条件模式匹配示例
以下程序显示了如何使用条件模式匹配。
let conditionalPatternMatching x y =
match (x, y) with
| (x, y) when x>y -> printfn "X is greater than y"
| (x, y) when x<y -> printfn "Y is greater than x"
| _ -> printf "X = Y"
conditionalPatternMatching 20 10
输出:
X is greater than y
列表中的F#模式匹配
在F#中, 你可以在列表中应用模式匹配。让我们来看一个例子。
let listPatternMatching list =
match list with
| [var] -> var
| [var1;var2]-> var1+var2
printf "%d" (listPatternMatching [2;1])
输出:
3
元组中的F#模式匹配
你也可以在元组中使用模式匹配。让我们来看一个例子。
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)
评论前必须登录!
注册