开发者

Implementing F# Workflow builders: Yield, For, YieldFrom

I am trying to work on my understanding of F# workflow builders. So I came up with the following example for purposes of experimentation.

type failSafeSeq() =
    member this.For(seq, mapFunction) = seq |> Seq.map mapFunction
    member this.Yield(yieldExpr) = yieldExpr
    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) }

With the above code, compilation fails at "(allFilesSeq subdir)" with the error message:

This expression was expected to have type     string     but here has type     seq<string>

I have tried numerous different incantations to fix this error, but without success. What am I missin开发者_运维知识库g?


type failSafeSeq() =
    member this.For(seq, mapFunction) = Seq.collect mapFunction seq
    member this.Yield(yieldExpr) = Seq.singleton yieldExpr
    member this.YieldFrom(yieldBang) = yieldBang
    member this.Combine(a, b) = Seq.append a b
    member this.Delay(delayFun) = delayFun()
    member this.Zero() = Seq.empty 
  • For produces a sequence of sequences so you need to flatten them
  • Yield should wrap value in computation type - in your case produce sequence with one element
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜