Know Thy Option

A thing or two about Option

  • Avoid .get at all costs. Forget there is even a .get function on Option. There is always an alternative to .get. Same applies to .head
  • If you are going to have access the value in an Option in a test class1, prefer extending your test class from OptionValues. Then you can use .value on an Option, which fails with a relatively better error message if the value is not defined.
  • Option maybe viewed as a sequence (of zero or one element). This is for convenience when working with Option, which is why see a .head on an Option.

Continue reading Know Thy Option


Non-FP to FP Conversion Caveat

Sometimes you learn the best from others; by watching. This post is based on such an instance. A fellow engineer on my team was investigating a nagging issue – partially-successful operations or rather operations that left data in an inconsistent state. It goes without saying that I take no credit for the time and effort spent on the investigation nor for the fix. I am just the messenger. And as a responsible programmer 🤓, I am sharing it with the rest of the world.

We use Scala in my team and have been trying to be (pure) functional (as much). Hmmm … trying to be functional? Yeah, because the truth is not always black and white.

Continue reading Non-FP to FP Conversion Caveat

A Rambling on Error Handling

In the early years, software applications were tiny, compared to what we build today. In any given application, one could say, there were only a handful of error scenarios to deal with. Besides, error reporting, if not error handling, lacked finesse. Just slap the user with something red enough, and just say An error occurred.

Continue reading A Rambling on Error Handling

JS Programming in C# – Immutability

Enough! JavaScript had us in its grip for long with its foot guns. The first time I heard the term Hoisting, I had no idea about it and misheard as hosting. You declare variables using var happily, and you have to come to peace with yourself that it is okay to hoist the vars (lift’em all to the top-most scope). I can’t believe JS convinced the rest of us that it was okay. Then came ES6 and saved us. let fixed the scoping. const provided immutability. At least now, you can say JavaScript supports functional programming.

JavaScript got feathers on its hat – let and const.

Continue reading JS Programming in C# – Immutability

Facets of Immutability

Immutability, the cornerstone of functional programming, has many facets.

Not every (mainstream) language supports all the facets; at least not per what each facet stands for. That’s what I will talk about today. The various facets of immutability from a theoretical perspective, and briefly show how some of the mainstream languages have adopted and support these facets in their own way.

Continue reading Facets of Immutability

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.

Continue reading JS Programming in C# – Local Functions

Thinking Currying !!!

Currying is a mathematical concept based on lambda calculus. It is a technique of operating on a function (taking multiple arguments) by splitting and capable of chaining into a series of single argument functions. It is very similar to what a human would attempt to do on paper. For example, if you have to add numbers 1 through 10, what would you do? Class II mathematics… 0 in hand, 1 in the mind, add 0 and 1, so 1 in the mind, then 2 in the hand, … up to 10. So we compute the addition with one argument at a time.

In the programming world, it is realized by transforming a n-arguments function into a (n-1) arguments function, which takes the remaining one argument. This transformation when applied recursively on each of the single argument functions is the chaining of single argument functions that I discussed earlier. Needless to say, currying is a gift of the functional programming world. In simple words, functional programming is about building functions from other functions, and so functions are treated as first class citizens (like data).

If currying is just transforming a n arguments function into a single argument function, then extension method too is an example of currying.

public static bool Replace(this IList srcList, int position, T item)
    // Imagine an implementation here.... 

So you would be using the Replace above without explicitly passing the source list to the method; one argument less.

list.Replace(2, newItem);
// instead of Replace(ilistObj, 2, newItem) if extension method was not invented. 

Isn’t that right? Yes, but that is not the currying from the conventional standpoint of functional programming.

For samples, we will not use the devil (any functional programming language) itself; instead we will use C#, which provides functional programming facilities. Alright, let us curry.

int Add(int x, int y)
    return x + y;

Or to be functional, we may (re)write:

Func adderFunc = (x, y) => x + y;

To curry out an increment function, we would write as follows:-

Func<int, Func> Incrementer()
    return num => Add(num, 1);

and we use it is as follows:-

var inc = Incrementer();

Is that not better and wise than writing Sum(5, 1)?

If currying is just transforming a n-arguments function into a single argument function, then we should be able to write a generic currying function.

Func<T1, Func> Curry(Func fn)
    return x => y => fn(x, y);

Func<int, Func> Adder = Curry(Add); 
var Incrementor = Adder(1);
var i = Incrementor(5); 

when we may not have actually encountered a compelling situations to use this in the past
But isn’t this all cryptic? So why would we want to do all such cryptic things when we have not encountered any such situation….in the past? Actually we have.

When simple principles are tough for us to understand, it is our grandma who helps us. Our grandma here is C++; although grandma called it binding.

In C++, many STL algorithms require a functor (roughly equivalent to a function definition) with one argument, where as the desired function was a two or more arguments function. Then we use std::bind1st or std::bind2nd to curry it into unary function.

For instance, the count\_if algorithm calculates the number of elements in a sequence that satisfy the predicate, which happens to be a unary function. Suppose we want to count the even numbers in a collection of whole numbers (and imagine this to be a tough calculation). If there was a function that could take a number and return true if it was an even number, it could be fed to count_if. But what if we had a function like the one below – a two argument function.

bool IsDivisible(int number, int divisor)
    return number % divisor == 0;

The functor we need is nothing but an IsDivisible function with the second argument as 2. We could write an IsEven function which in turn calls IsDivisible. But that could be tedious one we were write such wrappers for a function with 10 arguments. In situations like this, we curry. In C++, we (use) bind.

std::bind1st – A helper template function that creates an adaptor to convert a binary function object into a unary function object by binding the first argument of the binary function to a specified value.

std::bind2nd – A helper template function that creates an adaptor to convert a binary function object into a unary function object by binding the second argument of the binary function to a specified value.

So in our case, we will be usingbind2nd, as follows:-

std::vector wholeNumbers = { 1, 2, 4, 5, 6, 7, 9, 10, 12, 15, 17, 20 };

    std::bind2nd(IsDivisible, 2)); 

Unfortunately, C++ stayed with bind1st and bind2nd, and currying was not that evident or securely possible since C++ did not have required facilities, say something like the C# delegate. So the concept has been in vogue from long time ago. Like every paradigm in programming, functional programming requires (re)aligning our thought (process). Instead of treating functions as just reusable pieces of code (as considered in procedural programming), they have to be conceived as the input processors, which may return either data or whole new function.

So that is a quick thought on Currying. I will try to share a few other thoughts related to currying, slightly expanding to functional programming but later.