Is there a standard option workflow in F#?

烂漫一生 提交于 2019-12-19 05:03:04

问题


Is there an option (maybe) wokflow (monad) in the standrd F# library?

I've found a dozen of hand-made implementations (1, 2) of this workflow, but I don't really want to introduce non-standard and not very trusted code into my project. And all imaginable queries to google and msdn gave me no clue where to find it.


回答1:


There's no Maybe monad in the standard F# library. You may want to look at FSharpx, a F# extension written by highly-qualified members of F# community, which has quite a number of useful monads.




回答2:


There's no standard computation builder for options, but if you don't need things like laziness (as added in the examples you linked) the code is straightforward enough that there's no reason not to trust it (particularly given the suggestively named Option.bind function from the standard library). Here's a fairly minimal example:

type OptionBuilder() =
    member x.Bind(v,f) = Option.bind f v
    member x.Return v = Some v
    member x.ReturnFrom o = o
    member x.Zero () = None

let opt = OptionBuilder()



回答3:


I've create an opensource library FSharp.Interop.NullOptAble available on nuget.

It not only works as an option workflow, but it works as a null or nullable workflow as well.

let x = Nullable(3)
let y = Nullable(3)
option {
    let! x' = x
    let! y' = y
    return (x' + y')
} (* |> should equal (Some 6) *)

Works just as well as

let x = Some(3)
let y = Some(3)
option {
    let! x' = x
    let! y' = y
    return (x' + y')
} (* |> should equal (Some 6) *)

Or even

let x = "Hello "
let y = "World"
option {
    let! x' = x
    let! y' = y
    return (x' + y')
} (* |> should equal (Some "Hello World") *)

And if something is null or None

let x = "Hello "
let y:string = null
option {
    let! x' = x
    let! y' = y
    return (x' + y')
} (* |> should equal None *)

Finally if you have a lot of nullable type things, I have a cexpr for chooseSeq {} and if you yield! something null/None it just doesn't get yielded.

See more examples here.



来源:https://stackoverflow.com/questions/7818277/is-there-a-standard-option-workflow-in-f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!