My understanding of monads is still being formed. I understand that aside from being associative, the other three contracts that a monad has to adhere to are identity
, pure
and bind
.
I infer that the constructor of Nullable<T>
forms the pure function, I do not see any identity
and bind
functions on Nullable<T>
.
.Net does not contain the bind
method for Nullable<T>
, but it gives you enough to build one yourself:
static Nullable<T2> Bind<T1, T2>(Nullable<T1> source, Func<T1, Nullable<T2>> f)
where T1 : struct where T2 : struct
{
return source.HasValue ? f(source.Value) : null;
}
C# does contain something similar (but less general) than bind
: the null conditional operator ?.
. Assuming a
is of type Nullable<T1>
and B
is a property of type Nullable<T2>
, then a?.B
is equivalent to Bind(a, x => x.B)
.