1

在 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不显式使用计算构建器功能的情况下使用?

4

2 回答 2

3

您可以创建嵌套表达式:

let! current = age { return a }
let! future = age { return (current + y) }

尽管您可以let改用:

let current = a
let future = current + y

请注意,这个构建器违反了单子定律,因为

return 150 >>= return不一样return 150

于 2014-07-08T11:55:24.757 回答
0

我已经更详细地研究了这个问题,我想我已经找到了一个合理的替代方法来使用age { return <expr> }Lee 在他的回答中显示的语法。

我对这种语法的主要不满是我们已经在agemonad 中,因此return正文中的任何语句都应该自动解析为age.Return. 但是,修复这个问题对于 F# 团队来说可能是非常低的优先级,因为解决方法非常简单。

我的替代方法是用一个函数重载该Bind方法,该函数取一个值,然后将其提升;然后将此提升的值发送到另一个Bind函数:

type Age =
| PossiblyAlive of int
| NotAlive

type AgeBuilder() =
    let reasonableAge (x:int) = x >= 0 && x <= 120

    member __.Return x = 
        if reasonableAge x then PossiblyAlive x else NotAlive

    member __.Bind(x:Age, f) =
        match x with
        | PossiblyAlive x when reasonableAge x -> f x
        | _ -> NotAlive

    member this.Bind(x:int, f) =
        this.Bind(this.Return(x), f)

let age = new AgeBuilder()

let willBeThere (a:int) (y:int) =
    age { 
        let! current = a
        let! future = (current + y)
        return future
    }
于 2014-08-01T23:05:01.553 回答