C# Functional style - Part 1

I have been learning about F# and functional programming lately. There is a great F# site explaining the functional concepts fsharpforfunandprofit.

There are some really interesting concepts like Partial Application of Arguments and Currying. I wonder on how we could bring these concepts to C# and how the could would look like with the latestC# 7 syntax.

I will take an example which comes up over-and-over, and walk through this example, improving it each step in C#.

In this part I will take a look at a very simple solution, avoiding using extensions methods and Func types. My goal is not to provide a mathematically equivalent solution, but rather than to see how the new syntax to simplify.

Let's have a method that adds together two numbers:

int Add(int x, int y) => x + y;

So if we say we would like to fix some of the parameters of this add method for always adding '1', we can create a new method:

int Add1(int x) => Add(x, 1);

Doing the same for Logging:

int Log(string message, int x)
{
  Console.WriteLine($"{message} Value: {x}");
  return x;
}

int LogInput(int x) => Log("Message In", x);
int LogOutput(int x) => Log("Message Out", x);

Now to composing these methods a 'RequestHandler' method, to Log the inputs and the outputs can create a new method, which invokes all in order:

int RequestHandler(int x) => LogOutput(Add1(LogInput(x)));

The problem with this is that it is probably hard to read (inside out), as we need to start from the 'x' at the end, apply LogInput, Add1 and LogOutput.

Finally, if we have an enumeration of integers, and we invoke them on the RequestHandler, we can do it rather simply:

public void Test()
{
  IEnumerable<int> input = Enumerable.Range(0, 3);
  input.Select(RequestHandler).ToList();
}

Note, that we need to have the ToList() called on Select if we want to enumeration to be evaluated.

Which has the following output:

Message In Value: 0Message Out Value: 1Message In Value: 1Message Out Value: 2Message In Value: 2Message Out Value: 3

In the coming posts, I will take a look on how we can elevate these methods to a higher level Func-s to achieve the same level of composition but with a more readable/fluent form.