True false operators for Maybe<T>
I added true & | operators for Maybe<T> which gives Maybe.NoValue a meaning that feels more like None in python or nil in ruby (more like nil than None). Now you can borrow ruby's initialization syntax:
private Maybe<int> theAnswer;
private void DoSomething()
{
// Initialize theAnswer to 42, if it doesn't already have a value
theAnswer |= 42;
}
likewise, you can also use || for null coersion now:
list.Select(x => x || 0);
I'm aware this is already available through other iSynaptic facilities, but this gives it a very fluent syntax and makes C# start to feel even more like those scripting languages you've used.
Thanks for the pull request! I'll take a look at it.
I'm really liking the addition of the | (or) operator. I need to update it to be lazily evaluated, but that is really going to clean up some code I'm working on! Can't believe I didn't think of that - nice catch!
I'm not so sure about the addition of the true and false operators. It looks like (and I need to confirm this) all it offers is not having to type .HasValue. Additionally, testing HasValue should not be the norm; there should be an extension method that provides the desired logic, implicitly testing HasValue. Also, given that it could cause confusion when T is bool (e.g. Maybe<bool>) my knee jerk reaction is not to include the true or false operators. Thoughts?
the true operator is required in order to make || work. For instance, in a |= b the compiler tests first if a is true (Maybe.true(a)) and uses b depending on what it finds. So yeah, this is basically just an untra-sweet shortcut for HasValue.
I left the false operator not implemented because it's only required for making && operator work. However, the code won't compile if you remove the false operator.
I should clarify a little more. The difference between | and || is that || short circuits, which requires the true operator. The trouble with | is that it always evaluates both sides, so in a |= b the compiler has b evaluated even if it won't be used. What you really want is a ||= b, but the c# compiler rejects it. So until they create a ||= operator, you're stuck with the longer a = a || b. Because of this behavior, this pull request isn't quite as groundbreaking as it could have been, but the |= still is pretty cool.
I knew the || operator uses the true operator for short-circuiting. However, we don't need the compiler short-circuiting with Maybe<T>. It already has built in support for lazy evaluation and short-circuiting. So, leaving out the true operator would only allow the | operator to be used, but it would still behave the way you want - even when you use the |= operator.
Take a look at the Or extension method. That shows how you can "or" together two maybes without evaluating them. I would just move that code into the | operator code.