Implementing F # Workflow Constructors: Handling Exceptions in for..in..do Constructions

Continuing to explore the constructors of the F # workflow, I decided to experiment with exception handling in the builder, in particular in the "for..in..do" construct.

The ultimate goal of this experiment is a workflow builder that will continue to process the sequence, even if an exception occurs.

Below, for example, does not work, because the For method for the constructor does not appear to be called until an exception point occurs (the first time Directory.EnumerateFiles (dir) is called)

type failSafeSeq() =
    member this.For(seq1, mapFunction) =
        try
            seq1 |> Seq.collect mapFunction
        with
            ex -> Console.WriteLine ex
                  Seq.empty
    member this.Yield(yieldExpr) = yieldExpr |> Seq.singleton
    member this.YieldFrom(yieldBang) = yieldBang
    member this.Combine(a, b) = Seq.append a b
    member this.Delay(delayFun) = delayFun()
    member this.Zero() = Seq.empty 

let failSafe = new failSafeSeq();

let rec allFilesSeq dir =
    failSafe { for file in Directory.EnumerateFiles(dir) do yield file
               for subdir in Directory.EnumerateDirectories dir do yield! (allFilesSeq subdir) }

[<EntryPoint>]
let main args =
    allFilesSeq "C:\\System Volume Information\\" //almost guaranteed to cause an UnauthorizedAccessException on Windows systems at the first Directory.EnumerateFiles(dir) call.
    |> Seq.iter Console.WriteLine
    0

Is this possible using F # workflows?

+3
source share
1 answer

; spec ,

... for pat in expr do cexpr ...

... b.For(expr, fun pat -> cexpr) ...

, expr For, , , , For .

, , seq , , Seq.collect (, , , , ).

- " seq s"... , , , , , seq .

? " seq" , ?

+1

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


All Articles