Search code examples
f#computation-expression

How can I call bind on a computation expression without the let keyword?


Say I have this:

MyComputationExpression {
    let! addr = Salesrecord.Address
    let! name = Salesrecord.Name
    return (name + " " + addr)
}

Is there any way to "unwrap" (call the bind method on) the address and name on the fly? Sort of like:

MyComputationExpression {
    (Salesrecord.Name! + " " + Salesrecord.Address!)
}

(If ! was the operator for unwrap on the fly). It seems a bit verbose to have to declare a new variable every time I want to use the result of bind just once.


Solution

  • Bind and Return methods are available on MyComputationExpression. Your original code is converted to this equivalent code:

    MyComputationExpression.Bind(
        Salesrecord.Address,
        fun addr -> MyComputationExpression.Bind(
            Salesrecord.Name,
            fun name -> async.Return (name + " " + addr)))
    

    This is quite ugly code, which is why computation expressions exist as a language feature. Being able to use them inline in the way that you want is currently not possible. It would be an additional language feature and it has been suggested before.