JS Programming in C# – Local Functions

Functional programs treat functions and data alike. No discrimination, if you will. That means, you can declare and use functions – assign to variables, pass to other functions etc., the same way you would play with variables.

A canonical example of a functional program would show how to pass functions as parameters to other functions (higher order functions). It would also show how one can create functions on the fly (lambdas or anonymous functions) and also assign it to a variable, which is of a predefined function type; either the compiler deduces or aligns to the calling context.

There is one important attribute of data that is mostly forgotten. It can be declared almost anywhere, particularly within functions. Local variables, remember? If we agree to treat data and functions alike then we should be able to declare a function inside another. Errrk! Why would anyone want to do that? Seems like JavaScript.

Indeed, it is. JavaScript, propagandized to have solely carried the torch of functional programming in to main stream programming, has supported declaring functions within functions since its time began.

If function H is declared within another function F then we call function H a local function or an inner function_1. I’ll stick to _local function to go with the title of the post.

It is no brainer declaring a local function but here is how it goes:

// This is JavaScript!
function giveMeSomething(name, age, height) {
  // A function declared within another and is
  // not visible out its parent, just like any
  // other variable
  function district9(age, height) {
    Say some pretty long and hairy logic
    to determine whatever

  // ...

  // The local function being consumed here.
  // But what has bonus got to do with age
  // and height? 😝
  let bonus = district9(age, height)

  // ...

That’s pretty straightforward. Let us ignore the details (shotguns) how much JavaScript is consistent2 in treating data and variables alike; or not.

Let me tell you why I think local functions are a must for any language that wishes to embrace functional-style programming.

Typical examples of a local function like district9 demonstrate abstraction of a piece of logic within a function providing separation of concerns, readability, and, to our advantage, restricting access to the local function, just like a variable. It’s undeniable. However, in all likelihood, a highly disciplined code (base) will not be sold only on the above mentioned advantages of local functions. Because, in a highly disciplined code base, whatever the local function is trying to abstract or separate out, it is probably available using existing libraries and utilities that are already not local. They are ubiquitous and general-purpose.

Let me borrow a rough analogy to prove my point. If you have programmed in C++ for a while, you too would be inclined to program in headers. C++ header files are a great way to establish reuse. If you can cram your logic in header files, you got something that is truly reusable3. In other words, all you have to do use it is include it. There are tons of libraries solely based on headers – Boost, Spirit, PEGTL and many more.

Languages that are not based on header files try to find an alternative. C# has classes. If we consider, not strictly, static classes equivalent to headers, I would like to have only public methods, no private methods, in static classes. I mean for a cleaner distribution. Private methods are sort of an interference to the facade (although header files still can have private methods). It’s all about packaging.

Consider the following example4 in JavaScript. You can imagine the same in C#.

function count(chars, ch)
    return count(chars, ch, chars.length - 1);

function count(chars, ch, high)
    if (high == -1)
        return 0;

    return (chars[high] == ch ? 1 : 0)
      + count(chars, ch, high - 1);

The above sample in C# would be declaring the helper function function count(chars, ch, high) as private. The other public counterpart just acts an entry point. Just like we have the tailrec annotation or keyword in some languages to hint the compiler, I believe some years from now, we would be able to define a single method with hints for parameters, although declared with the method signature, are accessible only during or for recursion. Such a thing is for the future. Until then local functions come to the rescue.

Here is the lovely C# version of the same method:

public static int Count(char[] chars, char ch)
    return Count(chars, ch, chars.Length - 1);

    int Count(char[] cs, char c, int h)
        if (h == -1)
            return 0;

        return (cs[h] == c ? 1 : 0)
            + Count(cs, c, h - 1);

Introduction of local functions in C# is yet one another feat towards treating data and functions alike. You can declare methods within methods in C# just like you would declare variables within a method.

You should have noticed that I declared the local function after the return statement. Consider it a convenience to organize or place local functions anywhere you like within its parent method. Anywhere where you think will improve readability.

Imagine you are writing tens of methods to help with a Tree data structure – traversal of all kinds, inquiry of all kinds etc. A lot of these methods are bound to be implemented using recursion. It is nice and handy to employ local functions such that when you take a look at the TreeHelpers.cs, you see only public methods. Pleasant sight for sore eyes, eh!

If we call functions taking functions as parameters as higher-order functions, should we call functions that declare functions within as lower-order functions? 😝

  1. I like the name inner function too because it is in sync with inner class, the same way you call a class that is defined inside another. Yeah, yeah, you are not supposed to use classes in JavaScript, and all ES201X is all blasphemy. But I’ll let you settle that matter with Douglas Crockford and others. Anyways, inner function breaks the philosophy of treating data and functions alike because there isn’t an inner variable. But there are local variables. So, local functions win this petty argument. 😜 
  2. One difference I found was local functions are hoisted similar to vars. But unlike lets or scoped variables, local functions do not have an equivalent. I think this difference is due to historical reasons. JavaScript has always been functional supporting local functions and hoisting. let came later. BTW, letting a function declaration is inclined towards more towards anonymous functions and lambdas than declaring a function like a regular variable. 
  3. You did not see me sweeping static variables under the rug, did you? 😜 
  4. I leaned on Google/Stackoverflow for an example of recursion that relies on a helper function: https://stackoverflow.com/questions/22639797/recursive-helper-method/22640224#22640224 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s