【问题标题】:How to bind i at the end of a sequence using Seq.iteri如何使用 Seq.iteri 在序列末尾绑定 i
【发布时间】:2009-07-25 07:45:59
【问题描述】:
我的序列 |> Seq.iteri (fun i x -> ...) ...

如何在序列末尾绑定 i?也就是说,如何绑定表示iteri迭代次数的值?

当然我可以创建一个 ref 并为所有迭代分配 i,但我想知道是否有更优雅的方式?

【问题讨论】:

    标签: f# sequence loops


    【解决方案1】:

    你可以使用fold,这样

    Seq.iteri (fun i x -> ...)
    

    变成

    Seq.fold (fun i x -> ... ; i+1) 0
    

    沿着这些方向:

    let aSeq = 
        seq {
            for i in 1..10 do
                printfn "eval %d" i
                yield i
        }
    
    let r = 
        aSeq 
        |> Seq.fold (fun i x ->
            printfn "iter %d" x // or whatever is "..."
            i+1) 0     
    
    printfn "result: %d" r
    

    【讨论】:

    • 对我来说,折叠是真正改变了我解决问题的方式的实用习语之一。如果可以的话,你应该花点时间和他们在一起。
    • 谢谢gradbot,感谢鼓励!
    【解决方案2】:

    据我了解,您可以使用直接返回传递给 Seq.iteri 的序列长度的函数(因为 Seq.iteri 将遍历整个序列)。这将是更多函数式编程方式,而不是考虑可变变量:

    Seq.length mySequence
    

    在你的情况下:

    mySequence |> Seq.iteri (fun i x -> ...)
    let i = Seq.length mySequence
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-29
      • 1970-01-01
      • 1970-01-01
      • 2020-01-05
      • 1970-01-01
      • 2021-02-14
      • 1970-01-01
      相关资源
      最近更新 更多