【问题标题】:Get count of true in bool[,] F#在 bool[,] F# 中获取 true 的计数
【发布时间】:2014-08-01 06:03:19
【问题描述】:

我在 F# 中有一个 bool[,] 并且我想获取 true 的存在数。我如何在不深入到命令式编程的情况下做到这一点?

这是我目前的解决方案,实际上只是用 f# 编写的 c#。

let mutable x = 0
for cell in cells do
    if cell = true then x <- x + 1
x

【问题讨论】:

    标签: arrays multidimensional-array f#


    【解决方案1】:

    这是一种方法:

    let x = cells |> Seq.cast |> Seq.filter id |> Seq.length
    

    它的作用是过滤掉 false 值(参见 Seq.filter),然后只计算剩下的值。

    【讨论】:

    • 不需要类型注解,一个序列的元素个数由Seq.length返回,那就是cells |&gt; Seq.cast |&gt; Seq.filter id |&gt; Seq.length
    • 哈,是的,我在发帖前没有正确检查这个太糟糕了!感谢您的更正。
    • 不错。在如此简短的声明中发生了很多事情。美丽的。谢谢
    【解决方案2】:

    一种方法是使用seq,然后使用Seq.sumBy

    cells |> Seq.cast<_> |> Seq.sumBy (function |true -> 1 |false -> 0);;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-05
      • 2016-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-21
      • 2012-10-21
      • 2020-11-14
      相关资源
      最近更新 更多