Skip to content
This repository was archived by the owner on Sep 1, 2021. It is now read-only.

Functions

Tolik Pylypchuk edited this page May 30, 2018 · 9 revisions

Predefined functions

The predefined functions are implemented as extension methods in the Function class.

Identity

The Identity<T> function simply returns the provided argument.

Cast and UnsafeCast

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 compile

The UnsafeCast<TFrom, TTo> function returns the provided argument as a value of type TTo using the as operator.

IsNull and IsNotNull

The IsNull and IsNotNull functions can be used to determine whether an object is null or not.

Function Currying

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.

Clone this wiki locally