PASSING FUNCTIONS

A very simple approach to lazy evaluation is preferring higher order functions where possible. Consider this piece of imperative code:

private static int BigCalculation( ) {

  Console.WriteLine("BigCalculation called");

 

  return 42;

}

 

private static void DoSomething(int a, int b) {

  Console.WriteLine("DoSomething called");

 

  if (a != 0)

    Console.WriteLine(b);

}

The function BigCalculation is meant to model a function that takes a very long time to return its result. It may actually be a calculation, or it may be a process that takes long to complete for other reasons.

The function DoSomething is entirely unconnected, it takes two parameters, a and b, and does something with b depending on a. In fact, it is not really relevant that the action depends on a; in reality it could depend on a whole number of circumstances outside the scope of the function. Imperative programming is all about the management of state, so there are typically many external details that influence the precise code path through any given function. In this example, the line of code that “does something with” b simply outputs the value on the console, which is again a placeholder for any other kind of action that requires the value of b.

Now, in an imperative application a call into this function might well look like this:

DoSomething(0, BigCalculation());

It doesn’t have to be a literal zero that is passed as the first parameter; it could be a variable instead. The important thing ...

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.