Can I intercept the F # sequence generator?

trying to get around the problem in an external library - is there a way to try to catch the generator element itself by element (maybe not, but just to make sure ...)?

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) () 
+6
source share
1 answer

You can not. As soon as an exception occurs, the state of the source enumerator is confused. If you cannot enter the original counter to โ€œlock inโ€ its state, you cannot force it to continue to create values.

You can, however, make the whole process โ€œstoppedโ€ after an exception, but you need to go below the level and work with 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") 
+7
source

Source: https://habr.com/ru/post/987701/


All Articles