f# - 我的匹配看起来很笨重,有没有更好的方法来编码?

标签 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

最佳答案

可能最简洁的版本是使用 List.tryPick :

let getIndex connDB strTable =
  [ getIndexByPrimaryKey;
    getIndexByCluster;
    getIndexByFirstColumns;
    getIndexByOnlyUnique;
    getAnyUniqueIndex; ]
  |> List.tryPick (fun fn -> fn connDB strTable)

更新:

该技术可以很容易地扩展到使用闭包,因此它适用于具有不同参数的函数(还有很多 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())

关于f# - 我的匹配看起来很笨重,有没有更好的方法来编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12610745/

相关文章:

.net - 为什么 F# 不支持“编辑并继续”?

scala - 通过与Array进行模式匹配进行的多重分配不适用于大写val

ruby-on-rails - 如何从 Rails 4.0.2 Controller 中的选择标签中获取所选选项

jQuery 返回选择列表中的第一个匹配项

string - 检查字符串是否为空或在Scala中不存在

f# - 如何使用正则表达式检查字符串是否为日期 F#

debugging - 通过调试“阅读”代码

F# 柯里化(Currying)示例

regex - 以编程方式,Youtube Content ID如何工作?

pattern-matching - 匹配复杂的继承-y 东西