F#计算表达式和返回语句

F#计算表达式和返回语句,f#,monads,computation-expression,F#,Monads,Computation Expression,在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

在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
  }
let! current = age { return a }
let! future = age { return (current + y) }
将是:

let! current = return a
let! future = return (current + y)
但是它不起作用。我最接近的是:

let! current = age.Return a
let! future = age.Return (current + y)

但这看起来很脏。是否有任何方法可以使用
return
,而不显式使用计算生成器函数

您可以创建嵌套表达式:

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
  }
let! current = age { return a }
let! future = age { return (current + y) }
尽管您可以使用
来代替:

let current = a
let future = current + y
请注意,此生成器自


return 150>>=return
return 150

我已经更详细地研究了这个问题,并且我认为我已经找到了一个合理的替代方法,可以替代Lee在回答中显示的
age{return}
语法

我对这种语法的主要不满是我们已经处于
age
monad中,因此身体中的任何
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
    }
类型年龄=
|int的可能性
|不活着
类型AgeBuilder()=
设reasonalAge(x:int)=x>=0&&xfx
|现场直播
成员this.Bind(x:int,f)=
this.Bind(this.Return(x),f)
let age=new AgeBuilder()
让willBeThere(a:int)(y:int)=
年龄{
让!电流=a
让!future=(当前+y)
回归未来
}

你的代码对我有用-你得到了什么错误?没有错误-关于计算表达式语法和“return”语句。完美。。。回答了我的问题,也证实了我的怀疑,即“Return”定义没有进行边界检查,这有点“不确定”。