Cover by Oliver Sturm

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

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#. ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required