Skip to content

Instantly share code, notes, and snippets.

@mattfield
Last active December 26, 2015 07:59
Show Gist options
  • Save mattfield/7118535 to your computer and use it in GitHub Desktop.
Save mattfield/7118535 to your computer and use it in GitHub Desktop.
The Expression Problem

The Problem

We have data coming from one system and we want to use a library in another system to deal with it. However, the data is coming in in a format that doesn't match what the library expects. Square peg, round hole. In the OO world, we wrap the data (wrappers/adapters) that allow us to move the data into the library. There are a few problems with this, however. For example, you don't have a reference to the original data object you're actually using. In the functional world, where we don't tie behaviour to data, we alter the library itself to be able to accept the data we're being given.

Say we have a library that already supports the summation of lists such that:

    sum([1,2,3]) //=> 6
    sum(["a", "b", "c"]) //=> "abc"

These means that we have two different concepts of summation: an Addable kind for integers and a Foldable kind for strings; for integers it's just normal addition, and with strings it's a process of appending. There are a couple of basic requirements here: the library requires that elements are able to be added together, and it requires the concept of a "foldable" data structure.

However, we're getting our data in a tree:

        1
      /   \
    2      
  /   \   /   \
       4

The existing library currently only deals with lists by default, but it does expose concepts that deal with addition. Luckily, the contents of our tree nodes are addable! Now, if we were trying to do this in an OO world, we'd have to unwrap the entire data structure in order to get at the individuals pieces which we could then sum. This isn't very efficient. In a functional world, we can deal with this is a much more efficient way.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment