The msdn documentation for the Zero
method in computation expressions states that
Called for empty
else
branches ofif...then
expressions in computation expressions.
Assume we're using an identity
computation builder which does not have Zero
defined.
let IdentityBuilder() =
member this.Bind(i, f) = f i
member this.Return(i) = i
let identity = new IdentityBuilder()
The code below is allowed
identity {
printf "Hello World"
return 1
}
However, the following code is not allowed and fails with the compiler error
This control construct may only be used if the computation expression builder defines a 'Zero' method
identity {
if true then printf "Hello World"
return 1
}
Why does the compiler insist on calling Zero
for else
branches? What is the intuition behind this?
Whether or not an implementation of Zero
is needed is determined by how the if
statement is translated into function calls from the monadic syntax. If both branches of an if
are syntactically computation expressions then the translation does not involve Zero
. In the case
that one of the branches is not syntactically a computation expression or is missing the translated expression involves Zero
.
I'll go through the cases.
Both if
and else
are syntactically computation expressions
identity {
if true then return 1 else return 2
return 1
}
translates to:
identity.Combine(
if true then identity.Return(1) else identity.Return(2),
identity.Return(1)
)
A branch is missing
identity {
if true then return 1
return 1
}
translates to:
identity.Combine(
if true then identity.Return(1) else identity.Zero(),
identity.Return(1)
)
Both branches are specified but they are not syntactically computation expressions
identity {
if true then printf "Hello World" else ()
return 1
}
translates to:
identity.Combine(
if true then printf "Hello World" else (); identity.Zero(),
identity.Return(1)
)
The last case is somewhat interesting because the translation takes place even if the if
statement returns a valid monadic value the translation using Zero
still takes place. The last case also applies to an if
without an else
when the then
part is not syntactically a computation expression.
EDIT: I recently did a little more research and figured out that my original answer was incorrect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With