Is there a standard option workflow in F#?

时光总嘲笑我的痴心妄想 提交于 2019-12-01 02:08:39

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.

kvb

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

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.

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