我正在以类似的方式生成序列:
migrators
|> Seq.map (fun m -> m())
Run Code Online (Sandbox Code Playgroud)
该migrator函数最终返回一个受歧视的联合,如:
type MigratorResult =
| Success of string * TimeSpan
| Error of string * Exception
Run Code Online (Sandbox Code Playgroud)
我希望在map遇到我的第一次时停止,Error但我需要Error在最后的序列中加入.
我有以下内容向用户显示最终消息
match results |> List.rev with
| [] -> "No results equals no migrators"
| head :: _ ->
match head with
| Success (dt, t) -> "All migrators succeeded"
| Error (dt, ex) -> "Migration halted owing to error"
Run Code Online (Sandbox Code Playgroud)
所以我需要:
Error我很欣赏可能有一个不同的序列方法,除此之外map,我会对F#不熟悉并且在线搜索还没有产生任何东西!
我想这里有多种方法,但一种方法是使用展开:
migrators
|> Seq.unfold (fun ms ->
match ms with
| m :: tl ->
match m () with
| Success res -> Some (Success res, tl)
| Error res -> Some (Error res, [])
| [] -> None)
|> List.ofSeq
Run Code Online (Sandbox Code Playgroud)
注意List.ofSeq最后,那就是实现序列.另一种方法是使用序列理解,有些人可能会说它会产生更清晰的代码.