I'm trying to write a general monoidal pattern in C#, starting with a homogeneous function combining two non-null values, and returning either value if the other is null, or the combined value if neither is, or null. So I have this:
public static Func<TIn?, TIn?,TIn?> Drop2<TIn>(Func<TIn, TIn, TIn> f)
{
return (lhs, rhs) =>
{
if (lhs == null && rhs == null)
{
return default;
}
if (lhs == null && rhs != null)
{
return rhs;
}
if (rhs == null && lhs != null)
{
return lhs;
}
return f(lhs, rhs);
};
}
This looks fine and it even compiles, but when I try to use it, two odd things happen.
Func<int, int, int> sum = (lhs, rhs) => lhs + rhs;
var sumNonNull = DropNullable.Drop2(sum);
The Intellisense for sumNonNull shows as Func<int, int, int>?
, not the expected Func<int?, int?, int?>
, and I can't pass in null as either argument for sumNonNull (can't convert from int? to int).
Should this work? What am I missing?
Thanks in advance for any help