Jay*_*ayR 3 f# pattern-matching option
这似乎有效,但看起来很笨重.有没有更好的方法来编码?
// Hunting for the best index to use for a data compare
let getIndex connDB strTable =
match getIndexByPrimaryKey connDB strTable with
| Some(name) -> Some(name)
| None ->
match getIndexByCluster connDB strTable with
| Some(name) -> Some(name)
| None ->
match getIndexByFirstColumns connDB strTable with
| Some(name) -> Some(name)
| None ->
match getIndexByOnlyUnique connDB strTable with
| Some(name) -> Some(name)
| None ->
match getAnyUniqueIndex connDB strTable with
| Some(name) -> Some(name)
| None -> None
Run Code Online (Sandbox Code Playgroud)
可能最简洁的版本是使用List.tryPick:
let getIndex connDB strTable =
[ getIndexByPrimaryKey;
getIndexByCluster;
getIndexByFirstColumns;
getIndexByOnlyUnique;
getAnyUniqueIndex; ]
|> List.tryPick (fun fn -> fn connDB strTable)
Run Code Online (Sandbox Code Playgroud)
更新:
该技术可以很容易地扩展到使用闭包,因此它适用于具有不同参数的函数(还有很多fun
s :-)):
let getIndex connDB strTable =
[ fun () -> getIndexByPrimaryKey connDB strTable;
fun () -> getIndexByCluster connDB strTable;
fun () -> getIndexByFirstColumns connDB strTable;
fun () -> getIndexByOnlyUnique connDB strTable;
fun () -> getAnyUniqueIndex connDB strTable; ]
|> List.tryPick (fun fn -> fn())
Run Code Online (Sandbox Code Playgroud)