COMBINING APPROACHES

In pure functional programming, the two function construction approaches — composition and partial application — are commonly used to create new functions on the basis of existing ones. This is not the only possible approach; there’s always the alternative of defining a new function that calls one or more existing functions. Look at this example:

Func<int, Func<int, int>> add = x => y => x + y;

 

var add5PA = add(5);

 

Func<int, int> add5 = x => add(5)(x);

Both the add5PA and the add5 functions make use of the existing add function, and define a new function that will add 5 to its one remaining argument. This is a choice that’s always available when it comes to functional reuse, and there’s no general guideline as to when you should go for one or the other approach.

The main difference is that when using function construction techniques, you typically create a number of intermediate functions that perform part of the task at hand. When functions are constructed for the purpose of reuse within a single function, this might be irrelevant, but when they are created as parts of a larger functional framework, the intermediate functions might be usable in their own right. That is an advantage over the complete redefinition approach because there is no redundancy in the declarations.

The following paragraphs describe a use case for function construction that has been chosen purposefully because it is rather more complex than what you’d typically want to do in C#. ...

Get Functional Programming in C#: Classic Programming Techniques for Modern Projects now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.