I am trying to learn F# computation expressions. In general, what is the purpose of the Zero member?
What is its definition for sequences?
What is its definition for async workflows?
The Zero
member is used, for example, when you omit the else
branch in an if
expression:
comp { if b then return 1
return 2 }
... would be translated to something like this:
comp.Combine
( if b then comp.Return(1) else comp.Zero(),
comp.Return(2) )
How is it defined for standard computation types?
For asynchronous workflows, it is defined as asynchronous workflow that immediately returns a unit value - essentially equivalent to writing: async { return () }
.
For sequences (where you use yield
instead of return
) the Zero
member returns a sequence that does not return anything, corresponding to the standard Seq.empty
value.
If you want to read about some more theoretical background, then you can check out this paper. In a more theoretical terms, it says that Zero
is either going to be return ()
(when the computation is a monad) or it is going to be the unit of a monoid (when the computation is monoidal) which is something that Haskellers call mzero
.