Functional Programming made easy in C# with Language-ext
Read this article if you want to demystify Functional Programming and understand why and how to start using FP paradigms in C#.
In the title I have written FP and C# but the question you probably wonder is :
What the hell should we want to use FP paradigms in an OO language like C# ?
Here are some arguments to answer this question (from my POV) :
  • Write less code and more meaningful one : improved code clarity
  • Avoid side effects by using immutability and pure functions : Easier concurrent programming
  • Easier testing : it’s really easy to test functions
  • Easier debugging
  • Funnier to write

OK but why don’t we use a FP language instead of C# ?

In companies it’s really hard to change the habits. We don’t all work in the Sillicon Valley and in my reality the latest versions in the production environments are : Java 8, .NET Framework 4, NodeWhat ?, …
In my world organizations are not yet ready to invest in pure FP languages like F#, Kotlin, Clojure or whatever. They are stuck in legacy code…
To go further on this topic I invite you to watch this video on Functional Core, Imperative Shell : https://discventionstech.wordpress.com/2017/06/30/functional-core-and-imperative-shell/
It’s a pattern that could be really useful to every developers on earth I think.
  • Functional core (declarative) composed of pure functions (in / out) and easy to test without any mocks.
  • Imperative shell or reactive container the service logic that you can test with integration tests
Now I have proved the interest of FP in OO language let’s go for a quick lesson.

Let’s demystify Functional Programming (FP)

“In computer science, functional programming is a programming paradigm — a style of building the structure and elements of computer programs — that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data.” — wikipedia
Basically FP is all about functions and immutability :
  • Pure functions
  • Lambda functions (anonymous)
  • High order functions
  • Composition
  • Closures
  • Currying & partial application
  • Recursion
If you have already looked at it, you have probably read other words like functors, monads and monoïds that can be very scary but in reality concepts are not.
Let’s start by explaining 3 concepts :

Immutability

We never want to mutate an object in FP we want to avoid side effects so we prefer creating a new one. If we have mutable objects it could be possible for another function to mutate the object we were working on concurrently.
Immutability ensures a function remains pure, it makes concurrency much more easy to handle and makes our dev life easier.

Pure Functions

A pure function don’t refer to any global state. The same inputs will always get the same output.
Combined with immutable data types mean you can be sure the same inputs will give the same outputs.

Higher order function

A function that does at least one of the following:
  • Takes one or more functions as arguments
  • Returns a function as its result
A higher order function that takes 2 functions as arguments
Before demonstrating code I highly recommend you to read this great article about FP concepts (I won’t do better for sure) :
Now you know the basics behind FP we can start deep diving into Language-ext.

What is Language-ext ?

According to the creator of the lib Paul Louth : It’s a library that uses and abuses the features of C# to provide a functional-programming ‘base class library’ that, if you squint, can look like extensions to the language itself.
His desire here is to make programming in C# much more reliable and to make the engineer’s inertia flow in the direction of declarative and functional code rather than imperative.
It’s basically “one lib to rule them all” : https://github.com/louthy/language-ext

Language-ext vs LinQ

Yes FP paradigms in C# exist since the introduction of LinQ. Here is a mapping between some language-ext functionalities and their equivalence in LinQ :

Easy immutable record types

Implementing immutable data structures is a nightmare in OO languages (Equals, GetHashCode, IEquatable<A>, IComparer<A>, implementing operators: ==, !=, <, <=, >, >=).
That’s why there is a Record class in language-ext :
1
public class User
2
{
3
public readonly Guid Id;
4
public readonly string Name;
5
public readonly int Age;
6
7
public User(Guid id, string name, int age)
8
{
9
Id = id;
10
Name = name;
11
Age = age;
12
}
13
}
14
15
public class UserRecord : Record<UserRecord>
16
{
17
public readonly Guid Id;
18
public readonly string Name;
19
public readonly int Age;
20
21
public UserRecord(Guid id, string name, int age)
22
{
23
Id = id;
24
Name = name;
25
Age = age;
26
}
27
}
28
29
[Fact]
30
public void record_types()
31
{
32
var spongeGuid = Guid.NewGuid();
33
34
var spongeBob = new User(spongeGuid, "Spongebob", 40);
35
var spongeBob2 = new User(spongeGuid, "Spongebob", 40);
36
37
Assert.False(spongeBob.Equals(spongeBob2));
38
39
// Use immutable records available in Language-ext
40
var spongeBobRecord = new UserRecord(spongeGuid, "Spongebob", 40);
41
var spongeBobRecord2 = new UserRecord(spongeGuid, "Spongebob", 40);
42
43
Assert.True(spongeBobRecord.Equals(spongeBobRecord2));
44
}
Copied!

No more out parameters

Yes in C# we have out parameters on TryParse for example now it’s finished :

Option

Many functional languages disallow null values, as null-references can introduce hard to find bugs. Option is a type safe alternative to null values. (it also exists in F#).
Avoid nulls by using an Option
An Option<T> can be in one of two states : some => the presence of a value none => lack of a value
1
Option<int> aValue = 2;
2
aValue.Map(x => x + 3); // Some(5)
3
4
Option<int> none = None;
5
none.Map(x => x + 3); // None
6
7
//Left -> Some, Right -> None
8
aValue.Match(x => x + 3, () => 0); // 5
9
none.Match(x => x + 3, () => 0); // 0
10
11
// Returns the Some case 'as is' -> 2 and 1 in the None case
12
int value = aValue.IfNone(1);
13
int noneValue = none.IfNone(42); // 42
Copied!
Match : match down to primitive type
Map : We can match down to a primitive type, or can stay in the elevated types and do logic using map.
  • Lambda inside map won’t be invoked if Option is in None state
  • Option is a replacement for if statements ie if obj == null
  • Working in elevated context to do logic

Lists are functors

We can map them :
1
new int[] { 2, 4, 6 }.Map(x => x + 3); // 5,7,9
2
new List<int> { 2, 4, 6 }.Map(x => x + 3); // 5,7,9
3
//Prefer use List (Immutable list)
4
List(2, 4, 6).Map(x => x + 3); // 5,7,9
Copied!

Function composition

What happens when you apply a function to another function? When you use map on a function, you’re just doing function composition :
1
static Func<int, int> Add2 = x => x + 2;
2
static Func<int, int> Add3 = x => x + 3;
3
4
static int Add5(int x) => Add2.Compose(Add3)(x);
Copied!

Bind

Monads apply a function that returns a wrapped value to a wrapped value. Monads have a function “bind” to do this.
Suppose half is a function that only works on even numbers.
What if we feed it a wrapped value? This is where bind comes in!
1
static Option<double> Half(double x)
2
=> x % 2 == 0 ? x / 2 : Option<double>.None;
3
4
[Fact]
5
public void bind_monad()
6
{
7
Option<double>.Some(3).Bind(x => Half(x));// None
8
Option<double>.Some(4).Bind(x => Half(x));// Some(2)
9
}
10
11
[Fact]
12
public void chain_bind_monad()
13
{
14
Option<double>.Some(20)
15
.Bind(x => Half(x))// Some(10)
16
.Bind(x => Half(x))// Some(5)
17
.Bind(x => Half(x));// None
18
}
Copied!

Try

Exception handling made easier the use of try. No more needs of ugly try/catch that pollutes the flow of your code you can describe your pipeline in a really readable way.
1
public void file_monad_example()
2
{
3
GetLine()
4
.Bind(ReadFile)
5
.Bind(PrintStrln)
6
.Match(success => Console.WriteLine("SUCCESS"),
7
failure => Console.WriteLine("FAILURE"));
8
}
9
10
static Try<string> GetLine()
11
{
12
Console.Write("File:");
13
return Try(() => Console.ReadLine());
14
}
15
16
static Try<string> ReadFile(string filePath) => Try(() => File.ReadAllText(filePath));
17
18
static Try<bool> PrintStrln(string line)
19
{
20
Console.WriteLine(line);
21
return Try(true);
22
}
Copied!
Here if something fails, you have the exception in the failure match part. The better part is that Try has a brother called TryAsync that is demonstrated in the real life example.

Memoization

Memoization is some kind of caching, if you memoize a function, it will be only executed once for a specific input.
1
static Func<string, string> GenerateGuidForUser = user => user + ":" + Guid.NewGuid();
2
static Func<string, string> GenerateGuidForUserMemoized = memo(GenerateGuidForUser);
3
4
[Fact]
5
public void memoization_example()
6
{
7
GenerateGuidForUserMemoized("spongebob");// spongebob:e431b439-3397-4016-8d2e-e4629e51bf62
8
GenerateGuidForUserMemoized("buzz");// buzz:50c4ee49-7d74-472c-acc8-fd0f593fccfe
9
GenerateGuidForUserMemoized("spongebob");// spongebob:e431b439-3397-4016-8d2e-e4629e51bf62
10
}
Copied!

Partial application

Partial application allows you to create new function from an existing one by setting some arguments.
1
static Func<int, int, int> Multiply = (a, b) => a * b;
2
static Func<int, int> TwoTimes = par(Multiply, 2);
3
4
[Fact]
5
public void partial_app_example()
6
{
7
Multiply(3, 4); // 12
8
TwoTimes(9); // 18
9
}
Copied!

Either

Either represents a value of two types, it is either a left or a right by convention left is the failure case, and right the success case.
1
public static Either<Exception, string> GetHtml(string url)
2
{
3
var httpClient = new HttpClient(new HttpClientHandler());
4
try
5
{
6
var httpResponseMessage = httpClient.GetAsync(url).Result;
7
return httpResponseMessage.Content.ReadAsStringAsync().Result;
8
}
9
catch (Exception ex) { return ex; }
10
}
11
12
[Fact]
13
public void either_example()
14
{
15
16
GetHtml("unknown url"); // Left InvalidOperationException
17
GetHtml("https://www.google.com"); // Right <!doctype html...
18
19
var result = GetHtml("https://www.google.com");
20
21
result.Match(
22
Left: ex => Console.WriteLine("an exception occured" + ex),
23
Right: r => Console.WriteLine(r)
24
);
25
}
Copied!

Fold vs Reduce (Aggregate in LinQ)

  • Fold takes an explicit initial value for the accumulator. The accumulator and result type can differ as the accumulator is provided separately.
  • Reduce uses the first element of the input list as the initial accumulator value (just like the Aggregate function). The accumulator and therefore result type must match the list element type.
1
[Fact]
2
public void fold_vs_reduce()
3
{
4
//fold takes an explicit initial value for the accumulator
5
//Can choose the result type
6
var foldResult = List(1, 2, 3, 4, 5)
7
.Map(x => x * 10)
8
.Fold(0m, (x, s) => s + x); // 150m
9
10
//reduce uses the first element of the input list as the initial accumulator value
11
//Result type will be the one of the list
12
var reduceResult = List(1, 2, 3, 4, 5)
13
.Map(x => x * 10)
14
.Reduce((x, s) => s + x); // 150
15
}
Copied!

Real life example

This example demonstrates the kind of usage you could have of language-ext in application services : chaining operations / pipelining, improve error handling, no more redundant checks, …
1
using System;
2
using System.Threading.Tasks;
3
using LanguageExt;
4
using static LanguageExt.Prelude;
5
6
namespace language_ext.kata.Account
7
{
8
public class AccountService
9
{
10
private readonly UserService userService;
11
private readonly TwitterService twitterService;
12
private readonly IBusinessLogger businessLogger;
13
14
public AccountService(UserService userService, TwitterService twitterService, IBusinessLogger businessLogger)
15
{
16
this.userService = userService;
17
this.twitterService = twitterService;
18
this.businessLogger = businessLogger;
19
}
20
21
private TryAsync<RegistrationContext> CreateContext(Guid userId) =>
22
TryAsync(() => userService.FindById(userId)).Map(user => new RegistrationContext(user));
23
24
private TryAsync<RegistrationContext> RegisterOnTwitter(RegistrationContext context) =>
25
TryAsync(() => twitterService.Register(context.Email, context.Name)).Map(context.SetAccount);
26
27
private TryAsync<RegistrationContext> AuthenticateOnTwitter(RegistrationContext context) =>
28
TryAsync(() => twitterService.Authenticate(context.Email, context.Password)).Map(context.SetToken);
29
30
private TryAsync<RegistrationContext> Tweet(RegistrationContext context) =>
31
TryAsync(() => twitterService.Tweet(context.Token, "Hello I am " + context.Name)).Map(context.SetTweetUrl);
32
33
private TryAsync<RegistrationContext> UpdateUser(RegistrationContext context) =>
34
TryAsync(async () =>
35
{
36
await userService.UpdateTwitterAccountId(context.Id, context.AccountId);
37
return context;
38
});
39
40
public async Task<Option<string>> Register(Guid id)
41
{
42
return await CreateContext(id)
43
.Bind(RegisterOnTwitter)
44
.Bind(AuthenticateOnTwitter)
45
.Bind(Tweet)
46
.Bind(UpdateUser)
47
.Do(context => businessLogger.LogSuccessRegister(context.Id))
48
.Map(context => context.Url)
49
.IfFail(failure =>
50
{
51
businessLogger.LogFailureRegister(id, failure);
52
return (string)null;
53
});
54
}
55
}
56
}
Copied!

Conclusion

Start using language-ext in your projects is a really good idea. This lib can make your life much more easier.
You can see it at your first step to go into the FP world, before one day be able to use a language like Clojure or F#.

Resources

All the source code is available in my github repository : https://github.com/ythirion/fp-in-csharp-sandbox.
If you want to go further :