Search code examples
f#computation-expression

Monadic operations on Choice<'T1,'T2>


I could not find an object choice in the standard libraries, that allows me to write

let safeDiv (numer : Choice<Exception, int>) (denom : Choice<Exception, int>) =
    choice {
        let! n = numer
        let! d = denom
        return! if d = 0
            then Choice1Of2 (new DivideByZeroException())
            else Choice2Of2 (n / d)
    }

like in Haskell. Did I miss anything, or is there a third-party library for writing this kind of things, or do I have to re-invent this wheel?


Solution

  • There is no built-in computation expression for the Choice<'a,'b> type. In general, F# does not have a built-in computation expression for the commonly used Monads, but it does offer a fairly simple way to create them yourself: Computation Builders. This series is a good tutorial on how to implement them yourself. The F# library does often have a bind function defined that can be used as the basis of a Computation Builder, but it doesn't have one for the Choice type (I suspect because there are many variations of Choice).

    Based on the example you provided, I suspect the F# Result<'a, 'error> type would actually be a better fit for your scenario. There's a code-review from a few months ago where a user posted an Either Computation Builder, and the accepted answer has a fairly complete implementation if you'd like to leverage it.