O'Reilly logo

Functional Programming in C#: Classic Programming Techniques for Modern Projects by Oliver Sturm

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required