Kurren
Kurren

Reputation: 837

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.

Upvotes: 3

Views: 101

Answers (2)

kaefer
kaefer

Reputation: 5741

Your specific example may be easily called from an operator, in order to be inlined:

let inline (+?) a b =
    MyComputationExpression(){
        let! x = a
        let! y = b
        return x + y }

Some 3 +? None
salesrecord.Address +? Some " " +? salesrecord.Name

In more complicated cases, the need to explicity execute bind on the remainder of the computation may at least improve readability.

Upvotes: 2

TheQuickBrownFox
TheQuickBrownFox

Reputation: 10624

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.

Upvotes: 4

Related Questions