Search code examples
f#monadsoption-typecomputation-expression

F# computation expression for nested Boolean tests?


I think I've got enough understanding of F# monads (workflows) that I see a few places in my code where implementing them makes sense.

For example, I've got a function with multiple nested if/thens, i.e. the function should continue only so long as the data pass certain "tests" along the way.

I'm familiar with the "maybe" monad, but in all the examples that I've seen, it's coded to operate on let! bindings, which I'm not doing. I'm hoping that someone can provide me with an example of the "maybe" workflow tailored for nested Boolean tests, not let binds.


Solution

  • I offered up a conditional workflow in response to a similar problem. I'll copy it here, for reference.

    module Condition =
      type ConditionBuilder() =
        member x.Bind(v, f) = if v then f() else false
        member x.Return(v) = v
      let condition = ConditionBuilder()
    
    open Condition
    
    let eval() =
      condition {
        // do some work
        do! conditionA
        // do some work
        do! conditionB
        // do some work
        do! conditionC
        return true
      }
    

    As you can see in the comments to my previous answer, not everyone's a fan. But it's interesting nonetheless.