Skip to main content

Sasa.Option - Handling Optional Values

This is the fourth post in my ongoing series covering the abstractions in Sasa. Previous posts:

Sasa.Option is an abstraction to deal with nullable/optional values. It is available in the core Sasa.dll. Reference types are already nullable, and structs have System.Nullable, so why write yet another abstraction to deal with optional values?

The answer is pretty simple: there is no other way to write a function whose generic arguments are clearly and plainly optional. This is partially complicated because C# doesn't consider type constraints when selecting method overrides, otherwise you could do something like this:

int Foo<T>(T nullable)
  where T : class
{
    ...
}
int Foo<T>(T notNullable)
  where T : struct
{
    ...
}

The nullable overload is clear from the type information, but this type information is never used and C# complains about ambiguous methods. Technically, you could simply write Foo like so:

int Foo<T>(T possiblyNull)
{
    if (possiblyNull == null)
        ...
    else
        ...
}

This will work even if you pass in Nullable<int> because a Nullable<int> can be compared to null, and so will take the proper branch. However, it's not at all clear from the type signature of Foo that possiblyNull is an optional Value. So Sasa.Option was created to easily specify this sort of contract, and have the contract enforced by the type system:

int Foo<T>(Option<T> possiblyNull)
{
    if (possiblyNull == null)
        ...
    else
        ...
}

Option<T> has safe implicit conversions from T, and comparisons to null are fully defined.

Sasa.Option<T>.Value

Sasa.Option encapsulates a Value that may or may not be there. The Value property of the Option<T> struct returns the encapsulated Value if it exists, or throws InvalidOperationException if no Value exists:

Option<int> someInt = 3;
Console.WriteLine(someInt.Value);
Option<int> noInt = null;
Console.WriteLine(noInt.Value); //InvalidOperationException
// output is:
// 3
// throws InvalidOperationException

This property is also required by IValue<T>, which Option<T> implements.

Sasa.Option<T>.HasValue

To check whether an Option<T> has a Value, just check the HasValue property as you would on a Nullable<T>:

Option<int> someInt = 3;
Option<int> noInt = null;
Console.WriteLine(someInt.HasValue);
Console.WriteLine(noInt.HasValue);
// output is:
// true
// false

This property is also required by the IOptional<T>, which Option<T> implements.

Sasa.Option<T>.TryGetValue

TryGetValue permits accessing the encapsulated Value without throwing an exception if the Value is null:

Option<int> someInt = 3;
int x;
if (someInt.TryGetValue(out x))
  Console.WriteLine(x);
else
  Console.WriteLine("null");

Option<int> noInt = null;
if (noInt.TryGetValue(out x))
  Console.WriteLine(x);
else
  Console.WriteLine("null");
// output is:
// 3
// null

This method is required by the IVolatile<T> interface, which Option<T> implements.

Sasa.Option<T>.| operator

The C# null coalescing operation, ??, is hard-coded to only apply to reference types or System.Nullable<T>. However, the short-circuiting logical-or operator can be overridden, and Option<T> does so to provide option-coalescing:

Option<int> someInt = 3;
Option<int> noInt = null;
Console.WriteLine(someInt || 99);
Console.WriteLine(noInt || 99);
// output is:
// 3
// 99

Sasa.Option.ToOption

The Sasa.Option.ToOption extension methods allow simple conversions to option types, given any Value T or any nullable struct Value T?:

Option<int> someInt = 3.ToOption();
Option<int> noInt = new int?().ToOption();
Console.WriteLine(someInt);
Console.WriteLine(noInt);
// output is:
// 3
// null

Sasa.Option.ToNullable

Given any Option<T>, where T is a Value type, we can easily convert this to a Nullable<T> type using the ToNullable extension method:

int? someInt = new Option<T>.ToNullable();
Console.WriteLine(someInt ?? 99);
// output is:
// 3

Sasa.Option.Try

The Sasa.Option.Try static methods enable clients to execute some piece of code that returns a Value into an Option<T>. If the delegate throws an exception, then Option<T>.None is returned:

Option<int> someInt = Option.Try(() => 3);
Option<int> noInt = Option.Try<int>(() => throw new Exception());
Console.WriteLine(someInt);
Console.WriteLine(noInt);
// output is:
// 3
// null

Sasa.Option.Do

Sasa.Option.Do is an extension method that performs an action specified by a delegate only if the Option<T> has a Value:

Action<int> print = Console.WriteLine;
Option<int> someInt = 3;
Option<int> noInt = null;
someInt.Do(print);
noInt.Do(print);
// output is:
// 3

Sasa.Option.Select

Sasa.Option.Select are extension methods implementing the LINQ select query pattern on Option<T> and Nullable<T>:

Option<int> someInt = 3;
Option<int> noInt = null;
Console.WriteLine(someInt.Select(x => x > 0));
Console.WriteLine(noInt.Select(x => x > 0));
// output is:
// true
// null

Sasa.Option.Where

Sasa.Option.Where extension methods implement the LINQ where clause for query patterns on Option<T> and Nullable<T>:

Option<int> someInt = 3;
Option<int> noInt = null;
Console.WriteLine(someInt.Where(x => x > 0));
Console.WriteLine(someInt.Where(x => x < 0));
Console.WriteLine(noInt.Where(x => x == 0));
// output is:
// true
// null
// null

Sasa.Option.SelectMany

The last essential LINQ operator, Sasa.Option.SelectMany implements all permutations of SelectMany with Nullable<T> and Option<T>, which enables you to use option values in queries:

var val = from y in new int?(2)
          from j in 7.ToOption()
          from x in (y + 2 + j).ToOption()
          select x;
Console.WriteLine(val);

var noval = from y in new int?(2)
            from j in new int?()
            from x in (y + 2 + j).ToOption()
            select x;
Console.WriteLine(noval);
// output:
// 11
// null

Comments

Popular posts from this blog

async.h - asynchronous, stackless subroutines in C

The async/await idiom is becoming increasingly popular. The first widely used language to include it was C#, and it has now spread into JavaScript and Rust. Now C/C++ programmers don't have to feel left out, because async.h is a header-only library that brings async/await to C! Features: It's 100% portable C. It requires very little state (2 bytes). It's not dependent on an OS. It's a bit simpler to understand than protothreads because the async state is caller-saved rather than callee-saved. #include "async.h" struct async pt; struct timer timer; async example(struct async *pt) { async_begin(pt); while(1) { if(initiate_io()) { timer_start(&timer); await(io_completed() || timer_expired(&timer)); read_data(); } } async_end; } This library is basically a modified version of the idioms found in the Protothreads library by Adam Dunkels, so it's not truly ground bre

Building a Query DSL in C#

I recently built a REST API prototype where one of the endpoints accepted a string representing a filter to apply to a set of results. For instance, for entities with named properties "Foo" and "Bar", a string like "(Foo = 'some string') or (Bar > 99)" would filter out the results where either Bar is less than or equal to 99, or Foo is not "some string". This would translate pretty straightforwardly into a SQL query, but as a masochist I was set on using Google Datastore as the backend, which unfortunately has a limited filtering API : It does not support disjunctions, ie. "OR" clauses. It does not support filtering using inequalities on more than one property. It does not support a not-equal operation. So in this post, I will describe the design which achieves the following goals: A backend-agnostic querying API supporting arbitrary clauses, conjunctions ("AND"), and disjunctions ("OR"). Implemen

Easy Automatic Differentiation in C#

I've recently been researching optimization and automatic differentiation (AD) , and decided to take a crack at distilling its essence in C#. Note that automatic differentiation (AD) is different than numerical differentiation . Math.NET already provides excellent support for numerical differentiation . C# doesn't seem to have many options for automatic differentiation, consisting mainly of an F# library with an interop layer, or paid libraries . Neither of these are suitable for learning how AD works. So here's a simple C# implementation of AD that relies on only two things: C#'s operator overloading, and arrays to represent the derivatives, which I think makes it pretty easy to understand. It's not particularly efficient, but it's simple! See the "Optimizations" section at the end if you want a very efficient specialization of this technique. What is Automatic Differentiation? Simply put, automatic differentiation is a technique for calcu