WHY DO A WHOLE ABSTRACTION?

As usual, concrete examples of the abstraction will help you understand why an abstraction makes sense. In Haskell there’s a monad called Maybe, which will be the subject of the first example. Consider this code:

var tree = new FCSColl::UnbalancedBinaryTree<string>( );

tree = tree.Insert("Paul");

tree = tree.Insert("Adam");

tree = tree.Insert("Bernie");

tree = tree.Insert("Willy");

tree = tree.Insert("Suzie");

Console.WriteLine(tree);

This instantiates an immutable tree with a few string values. You could now try to access those values by following the path along the tree branches:

Console.WriteLine(tree.Left.Left.Left.Value);

The problem is that this is unsafe. In the example, the structure of the tree would be such that the third Left evaluation throws an exception because there’s no branch to follow at that point. To be on the safe side, you’d have to write a much more verbose algorithm:

static string GetThirdLeftChild(FCSColl::UnbalancedBinaryTree<string> tree) {

  if (tree != null) {

    if (tree.Left != null) {

      if (tree.Left.Left != null) {

        if (tree.Left.Left.Left != null) {

          return tree.Left.Left.Left.Value;

        }

        else {

          return "No such child";

        }

      }

      else {

        return "No such child";

      }

    }

    else {

      return "No such child";

    }

  }

  else {

    return "No such child";

  }

}

Following is a little helper class called Maybe<T>. It’s is rather similar to the ...

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.