如果我有一个尝试将起始数字划分两次的函数。整个工作流程必须返回布尔值。
let divideBy bottom top =
if bottom = 0 then None
else Some (top/bottom)
let divideByWorkflow init x y =
match init |> divideBy x with
| None -> false
| Some a ->
match a |> divideBy y with
| None -> false
| Some b -> true
let good = divideByWorkflow 12 3 2
let bad = divideByWorkflow 12 3 0
以下构建器正确吗?
type BoolMaybe = BoolMaybe with
member __.Bind (expr, f) =
match expr with
| Some value -> f value
| None -> false
member __.Return expr = expr
let divideByWorkflow init x y =
BoolMaybe {
let! a = init |> divideBy x
let! b = a |> divideBy y
return true
}
我同意dzoukr的答案,我的看起来略有不同:
let divideBy bot top =
match bot with
| 0 -> None
| _ -> Some (top / bot)
let divideByWorkflow init x y =
Some init
|> Option.bind (divBy x)
|> Option.bind (divBy y)
|> Option.isSome
无需计算表达式,它似乎在这里没有增加任何好处。
imho没有理由使用计算表达式使其更复杂。我宁愿留下一些简单的功能,例如:
let divideBy bottom top =
if bottom = 0 then None
else Some (top/bottom)
let divideByTwoTimes init x y =
init |> divideBy x |> Option.bind (divideBy y)
let divideByWorkflow init x = divideByTwoTimes init x >> Option.isSome
它有效,但我认为它是不必要的特定的。如果您想使用CE,我宁愿定义一个普通的Maybe
CE,然后做
let divideByWorkflow init x y =
Maybe {
let! a = init |> divideBy x
let! b = a |> divideBy y
return true
}
|> Option.defaultValue false