-
Notifications
You must be signed in to change notification settings - Fork 0
Functions
The predefined functions are implemented as extension methods in the Function class.
The Identity<T> function simply returns the provided argument.
The Cast<T, TBase> function returns the provided argument as a value of type TBase which is a base type of T.
It can be used, for example, to cast Option<TDerived> to Option<TBase>. Because .NET does not support variance in classes, Option<Base> is not the base class of Option<Derived>, so the cast must be used as a workaround.
using static CSX.Functions.Function;
class Base { }
class Derived : Base { }
// ...
void DoStuff(Option<Base> option) { }
// ...
var option = Option.From(new Derived());
DoStuff(option); // This will not compile
DoStuff(option.Map(Cast<Derived, Base>)); // However, this will compileThe UnsafeCast<TFrom, TTo> function returns the provided argument as a value of type TTo using the as operator.
The IsNull and IsNotNull functions can be used to determine whether an object is null or not.
If you aren't familiar with the concept of function currying, please read one of the many explanations available on the web.
The implementation of function currying is based on Mike Hadlow's blog post.
There are extension methods in the Function class to curry functions. They are defined for all Func types (17 total) and for all Action types (also 17). They are all called Curried.
Here's an example:
using CSX.Functions;
// ...
Func<int, int, int> add = (a, b) => a + b;
var curriedAdd = add.Curried();
var add4 = curriedAdd(4);
int nine = add4(5);Curried can be used with methods directly, though not as extension methods:
int Add(a, b) => a + b;
// ...
Function.Curried<int, int, int>(Add);Examples of usage are available here.