Is there a standard option workflow in F#?

前端 未结 3 1234
半阙折子戏
半阙折子戏 2021-01-07 17:01

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 w

3条回答
  •  再見小時候
    2021-01-07 17:41

    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.

提交回复
热议问题