F# computation expression for nested Boolean tests?

为君一笑 提交于 2019-12-23 19:12:59

问题


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.


回答1:


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.




回答2:


You could pull this off without defining a new monad. Just define

let test b = if b then Some () else None

which you can now use with maybe:

maybe {
    do! test (1 > 0)
    printfn "1"
    do! test (2 > 3)
    printfn "2"

    return ()
} 



回答3:


Both good answers, Daniel and eirik.

Daniels' answer led me to a solution that I had actually seen before, Tomas Petricek's implementation of an imperative workflow. I've decided to go with that, since it provides the best readability and is also useful in non-Boolean contexts.

Thanks, all.



来源:https://stackoverflow.com/questions/13710700/f-computation-expression-for-nested-boolean-tests

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