在 Try F# 网站上,他们给出了一个计算表达式的示例:
type Age =
| PossiblyAlive of int
| NotAlive
type AgeBuilder() =
member this.Bind(x, f) =
match x with
| PossiblyAlive(x) when x >= 0 && x <= 120 -> f(x)
| _ -> NotAlive
member this.Delay(f) = f()
member this.Return(x) = PossiblyAlive x
let age = new AgeBuilder()
let willBeThere (a:int) (y:int) =
age {
let! current = PossiblyAlive a
let! future = PossiblyAlive (current + y)
return future
}
这看起来有点像 Haskell 中的标准 Maybe monad。
但是,在真正的 Haskell 形式中,我想对两行使用 return:
let! current = PossiblyAlive a
let! future = PossiblyAlive (current + y)
成为:
let! current = return a
let! future = return (current + y)
但是它不起作用。我最接近的是:
let! current = age.Return a
let! future = age.Return (current + y)
但这看起来很脏。有什么方法可以在return
不显式使用计算构建器功能的情况下使用?