【问题标题】:F# exists where function?F# 存在于哪里函数?
【发布时间】:2017-08-23 12:26:52
【问题描述】:

我有一个处理 DataTable 的函数,用于查找具有特定值的列的任何行。它看起来像这样:

let exists = 
    let mutable e = false
    for row in dt.Rows do
        if row.["Status"] :?> bool = false
            then e <- true
    e

我想知道是否有办法在单个表达式中做到这一点。例如,Python 有一个“any”函数,它会做这样的事情:

exists = any(row for row in dt.Rows if not row["Status"])

我可以在 F# 中为我的 exists 函数编写类似的单行代码吗?

【问题讨论】:

    标签: f# where exists


    【解决方案1】:

    您可以使用Seq.exists 函数,该函数接受一个谓词,如果该谓词对序列的至少一个元素成立,则返回true。

    let xs = [1;2;3]
    let contains2 = xs |> Seq.exists (fun x -> x = 2)
    

    但在您的具体情况下,它不会立即起作用,因为DataTable.RowsDataRowCollection 类型,它只实现IEnumerable,而不是IEnumerable&lt;T&gt;,因此它不会被视为F# 意义上的“序列”,这意味着 Seq.* 函数将无法处理它。要使它们起作用,您必须首先使用 Seq.cast 将序列转换为正确的类型:

    let exists = 
       dt.Rows |> 
       Seq.cast<DataRow> |> 
       Seq.exists (fun r -> not (r.["Status"] :?> bool) )
    

    【讨论】:

    • 顺便说一句,F# 完全能够推断出序列表达式中的集合类型:seq{for r in dt.Rows -&gt; r.["Status"]} |&gt; Seq.forall unbox |&gt; not
    • 完美!简洁明了
    • 如果我的回答对您有所帮助,请考虑通过单击左侧的灰色复选标记将其标记为“已接受”。
    【解决方案2】:

    类似这样的东西(未经测试):

    dt.Rows |&gt; Seq.exists (fun row -&gt; not (row.["Status"] :?&gt; bool))

    https://msdn.microsoft.com/visualfsharpdocs/conceptual/seq.exists%5b%27t%5d-function-%5bfsharp%5d

    【讨论】:

    • 唉:错误 52 类型 'DataRowCollection' 与类型 'seq' 不兼容
    • 唉。我认为 IEnumerable 足以与 Seq 一起使用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-17
    • 2018-10-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多