Feeling In-Place with Functional

Functional programming paradigm has infiltrated every modern programming language. Functional is considered a safer coding method, and lends itself to parallelism as well. A typical function in function programming style takes an input and returns an output. Input can be a single item or an array. Output can be either as well. This enables cascading of functions, where the output of one function feeds to an input of another function, and so on, and so on…

Enumerable.Range(1, 100).Where(i => i % 20 == 0).OrderBy(i => -i)

But, what do we do when the available function is an in-place function, such as C# Array.Sort(), which performs sorts an array in-place – i.e. without allocating an additional array while sorting the input array. Array.Sort() takes an input array, but does not return an output array. Whatever shall we do? How do we use Array.Sort() in a functional way? How do we cascade it, in a functional style?

I posed this question to Dave Fancher, after his Functional C# talk at the Indianapolis .NET group. His answer was, “Even in-place functions should return their output.” Wow! Mind Blown! This concept is beautiful, as in-place functions would return their input array. This enables even in-place functions to be used in a functionally cascaded way. For non-functional use, this output can be simply ignored or using it doesn’t hurt anything.

I’ve implemented this concept in my HPCSharp open source C# nuget package, for several in-place functions, such as MSD Radix Sort, which can be implemented as in-place, and is a truly in-place function in the HPCSharp nuget package. Here is a usage example:

long[] ArrayOne = { 21, 43, 16, 5, 54, 3 };

var ListOne = ArrayOne.SortRadixMsdInPlaceFuncPar().ToList();

above code sorts an array of long integers using a truly in-place MSD Radix Sort algorithm, which also provides a functional interface, returning the input sorted array, which is then turned into a C# List. The name also indicates this to be an in-place functional method, to be explicit about it.

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 )

Facebook photo

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

Connecting to %s