【问题标题】:Can I intercept the F# sequence generator?我可以拦截 F# 序列生成器吗?
【发布时间】:2015-05-21 22:04:42
【问题描述】:

试图解决外部库中的问题 - 有没有办法逐项尝试捕获生成器本身(可能不是,但只是为了确定......)?

let myTest() =
    let mySeq = seq { for i in -3 .. 3 -> 1 / i }
    // how to keep the line above intact, but modify the code below to try-catch-ignore the bad one?
    mySeq |> Seq.iter (fun i -> printfn "%d" i)
    ()

【问题讨论】:

    标签: f# sequence


    【解决方案1】:

    你不能。
    一旦发生异常,源枚举器的状态就会被搞砸。如果你不能进入源枚举器来“修复”它的状态,你就不能让它继续产生值。

    但是,您可以在异常发生后使整个过程“停止”,但您必须达到以下级别并使用 IEnumerator<T>

    let takeUntilError (sq: seq<_>) = seq {
        use enm = sq.GetEnumerator()
        let next () = try enm.MoveNext() with _ -> false
        let cur () = try Some enm.Current with _ -> None
    
        while next() do
          match cur() with
          | Some c -> yield c
          | None -> ()
      }
    
    mySeq |> takeUntilError |> Seq.iter (printf "%d")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-23
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      • 2012-02-12
      • 1970-01-01
      相关资源
      最近更新 更多