2015-05-21 17 views
6

cercando di aggirare un problema nella libreria esterna - c'è un modo per provare a catturare il generatore stesso elemento per elemento (probabilmente no, ma solo per essere sicuri ...)?Posso intercettare il generatore di sequenza F #?

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) 
    () 

risposta

7

Non è possibile.
Una volta che si verifica l'eccezione, lo stato dell'enumeratore di origine è danneggiato. Se non è possibile accedere all'enumeratore di origine per "correggere" il suo stato, non è possibile farlo continuare a produrre valori.

È possibile, tuttavia, rendere l'intero processo di "stop" dopo l'eccezione, ma dovrete andare un livello inferiore e di lavoro con 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") 
Problemi correlati