Cover by Oliver Sturm

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

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

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required