{ "metadata": { "language": "haskell", "name": "", "signature": "sha256:08b3aec08cd7d08897ef00eb9c7209502812ae5e730117ac64771f1e9d784af5" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "In this notebook, we'll look at finger trees, a general purpose functional data structure developed in the [paper by Hinze and Patterson](http://www.soi.city.ac.uk/~ross/papers/FingerTree.html). Finger trees provide a functional sequence data structure, which provides amortized constant-time access and appending to the front and end of the sequence, as well as logarithmic time concatenation and random access. In addition to good asymptotic runtime bounds, the data structure turns out to be incredibly flexible: when combined with monoidal tags on the elements, finger trees may be used to implement efficient random-access sequences, ordered sequences, interval trees, and priority queues.\n", "\n", "Please note that all of the algorithms in this notebook are effectively sourced from the paper linked above; some of the images are also from the paper. I highly recommend reading the paper itself, before or after this guide." ] }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "# Developing the Data Structure\n", "\n", "The basis and motivation for finger trees comes from 2-3 trees. 2-3 trees are trees which can have two or three branches at each internal node and which have all of their leaves at the same level. While a binary tree of uniform depth $d$ must have $2^d$ leaves, 2-3 trees are much more flexible, and may be used to store any number of elements (the number does not have to be a power of two).\n", "\n", "Consider the following 2-3 tree (image taken from the original finger-tree paper linked above):\n", " \n", "\n", "This tree stores fourteen elements. Access to any of them requires three steps, and if we were to add more elements, the number of steps for each one would grow logarithmically. We would like to use these trees in order to model sequences. However, in many application sequences are very often accessed repeatedly at the front or back, and much less often in the middle. To accomodate this use case, we can modify this data structure to prioritize front and back access over other features. \n", "\n", "In our case, we add two *fingers*. A *finger* is simply a point at which you can access part of a data structure; in imperative languages, this would simply be a pointer. In our case, though, we restructure the entire tree and make the *parents* of the first and last children the two roots of our tree. Visually, consider taking the tree above, grabbing the first and last nodes on the previous-to-last layer, and pulling them up, letting the rest of the tree hang down:\n", " \n", "\n", "This new data structure is known as a *finger tree*. The finger tree is composed of several layers (boxed in blue below) which sit along its spine (the brown line):\n", " \n", "Each layer of the finger tree has a prefix (on the left) and a suffix (on the right), as well as a link further down the spine. The prefix and suffix contain values in the finger tree \u2013 on the first level, they contain values (2-3 trees of depth 0); on the second level, they contain 2-3 trees of depth 1; on the third level, they contain 2-3 trees of depth 2, and so on. This somewhat unusual property comes from the fact that the original 2-3 tree was of uniform depth. The edges of the original 2-3 tree are now at the top of the spine. The root of the 2-3 tree is now the very bottom element of the spine. As we go down the spine, we are traversing from the leaves to the root of the original 2-3 tree; as we go closer to the root, the prefix and suffixes contain deeper and deeper subtrees of the original 2-3 tree.\n", "\n", "With this description out of the way, let's go ahead and define this data structure. First, we must define the 2-3 tree structure which will be used to store things hanging off the spine:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "-- An intermediate node in a 2-3 tree, parameterized\n", "-- based on the type of its child.\n", "data Node a = Branch3 a a a -- The node can have 3 children.\n", " | Branch2 a a -- ...or only two children.\n", " deriving Show" ], "language": "python", "metadata": { "hidden": false }, "outputs": [], "prompt_number": 1 }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "Note that the node is parameterized by what type its child is. This allows nested nodes to be used to represent 2-3 trees, giving us a guarantee of uniform depth. For example, a 2-3 tree of depth 1 could be just aNode Char:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "-- The 2-3 trees at the 2nd layer suffix of our example finger tree.\n", "Branch3 'n' 'o' 't'\n", "Branch2 'a' 't'" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "display_data", "text": [ "Branch3 'n' 'o' 't'" ] }, { "metadata": {}, "output_type": "display_data", "text": [ "Branch2 'a' 't'" ] } ], "prompt_number": 2 }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "However, we can also create deeper 2-3 trees. For example, a 2-3 tree of depth 2 could be a Node (Node Char):" ] }, { "cell_type": "code", "collapsed": false, "input": [ "Branch2 (Branch3 'n' 'o' 't') (Branch2 'a' 't')" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "display_data", "text": [ "Branch2 (Branch3 'n' 'o' 't') (Branch2 'a' 't')" ] } ], "prompt_number": 3 }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "Note that this representation *guarantees* that 2-3 trees have uniform depth, because the depth is represented in the type of the tree. This has its own disadvantages (it's harder to write functions that are parametric over the depth of a tree), but will work well in our case.\n", "\n", "For later convenience, let's implement some utilities which let us treat Node values as lists of length two or three. This uses the OverloadedLists extension for GHC, which allows you to implement fromList and toList for different data types and then use pattern matching on them as if they were lists:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "-- Settings necessary to use fromList and toList on our data structures.\n", ":set -XOverloadedLists -XTypeFamilies\n", "import GHC.Exts (IsList(..))\n", "\n", "instance IsList (Node a) where\n", " type Item (Node a) = a\n", " \n", " toList (Branch2 x y) = [x, y]\n", " toList (Branch3 x y z) = [x, y, z]\n", " \n", " fromList [x, y] = Branch2 x y\n", " fromList [x, y, z] = Branch3 x y z\n", " fromList _ = error \"Node must contain two or three elements\"" ], "language": "python", "metadata": { "hidden": false }, "outputs": [], "prompt_number": 4 }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "Now that we have our 2-3 tree type, we need a type to store the prefix and suffixes that hang off the finger tree spine. If our finger tree is exactly analogous to a 2-3 tree, then the very first prefixes and suffixes can have either 2 or 3 elements, and intermediate ones can only have 1 or 2 (because one of the links goes up to the higher level in the spine). However, for the sake of uniformity, this requirement is relaxed for finger trees, and instead each prefix and suffix holds between 1 and 4 elements. (It must be 1, 2, 3, or 4 \u2013 no other values are allowed.) Although we could store the prefix and suffix in a list, we will instead devise a custom constructor that can only store the right number of elements:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "-- Parameterize the affix by the type of data it stores.\n", "-- This is equivalent to lists of length 1 to 4.\n", "data Affix a = One a\n", " | Two a a\n", " | Three a a a\n", " | Four a a a a\n", " deriving Show" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 5 }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "Working with these affixes is going to be somewhat tedious, so we'll quickly define some helper functions that treat these affixes as lists:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "-- Let affixes be treated as lists.\n", "instance IsList (Affix a) where\n", " type Item (Affix a) = a\n", " \n", " toList (One x) = [x]\n", " toList (Two x y) = [x, y]\n", " toList (Three x y z) = [x, y, z]\n", " toList (Four x y z w) = [x, y, z, w]\n", " \n", " fromList [x] = One x\n", " fromList [x, y] = Two x y\n", " fromList [x, y, z] = Three x y z\n", " fromList [x, y, z, w] = Four x y z w\n", " fromList _ = error \"Affix must have one to four elements\"\n", " \n", "-- The following functions could be much more efficient.\n", "-- We use the simplest implementation possible.\n", "affixPrepend :: a -> Affix a -> Affix a\n", "affixPrepend x = fromList . (x :) . toList\n", "\n", "affixAppend :: a -> Affix a -> Affix a\n", "affixAppend x = fromList . (++ [x]) . toList" ], "language": "python", "metadata": { "hidden": false }, "outputs": [], "prompt_number": 6 }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "Now that we've defined the data types necessary for storing values (the 2-3 tree storing the values and the affixes attached to the spine), we can create the spine data structure. This data structure is what we call the finger tree, and we define it as follows:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "-- As usual, the type parameter represents what type\n", "-- of data is stored in this finger tree.\n", "data FingerTree a \n", " = Empty -- We can have empty trees.\n", " | Single a -- We need a special case for trees of size one.\n", " \n", " -- The common case with a prefix, suffix, and link to a deeper tree.\n", " | Deep {\n", " prefix :: Affix a, -- Values on the left.\n", " deeper :: FingerTree (Node a), -- The deeper finger tree, storing deeper 2-3 trees.\n", " suffix :: Affix a -- Values on the right.\n", " }\n", " deriving Show" ], "language": "python", "metadata": { "hidden": false }, "outputs": [], "prompt_number": 7 }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "In the definition above, the deeper field of a FingerTree a has type FingerTree (Node a). This means that the values stored at the next level are 2-3 trees that are one level deeper. Thus, the affixes in the first layer of a FingerTree Char will just store Chars; the second layer will be a FingerTree (Node Char) and will have affixes that hold 2-3 trees of depth 1 (Node Char); the third layer will be a FingerTree (Node (Node Char)) and will have affixes that store 2-3 trees of depth 2 (Node (Node Char)).\n", "\n", "Now that we've defined our finger tree data structure, spend a little bit longer staring at the example tree from before, making sure that you understand how to translate that tree into a FingerTree Char:\n", " \n" ] }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "The translation of this tree is as follows:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "layer3 :: FingerTree a\n", "layer3 = Empty\n", "\n", "layer2 :: FingerTree (Node Char)\n", "layer2 = Deep prefix layer3 suffix\n", " where\n", " prefix = [Branch2 'i' 's', Branch2 'i' 's']\n", " suffix = [Branch3 'n' 'o' 't', Branch2 'a' 't']\n", "\n", "layer1 :: FingerTree Char\n", "layer1 = Deep prefix layer2 suffix\n", " where\n", " prefix = ['t', 'h']\n", " suffix = ['r', 'e', 'e']\n", "\n", "exampleTree :: FingerTree Char\n", "exampleTree = layer1\n", "\n", "exampleTree" ], "language": "python", "metadata": { "hidden": false }, "outputs": [ { "metadata": {}, "output_type": "display_data", "text": [ "Deep {prefix = Two 't' 'h', deeper = Deep {prefix = Two (Branch2 'i' 's') (Branch2 'i' 's'), deeper = Empty, suffix = Two (Branch3 'n' 'o' 't') (Branch2 'a' 't')}, suffix = Three 'r' 'e' 'e'}" ] } ], "prompt_number": 8 }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "# Finger Trees as Sequences\n", "\n", "The motivating reason behind developing our strange finger tree data structure was to have a sequence-like tree which could be accessed quickly at the front and back. Thus, in this section we implement operations that view finger trees as sequences.\n", "\n", "## Prepend and Append\n", "\n", "Let's begin by appending an element to the front of a finger tree. Ideally, we could prepend an element simply by prepending it to the prefix of the tree. While this would work for finger trees that have one, two, or three elements in their prefix, it would *not* work on a finger tree that has four elements in its prefix. In that case, we would be unable to add one more element to the prefix, because the prefix cannot have a length greater than four. To avoid a prefix of length five, we instead take three of these five elements, turn them into a Node using the Branch3 construction, and then prepend them to the deeper finger tree:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "-- Use <| to prepend. It's the finger tree analogue of : for lists. \n", "infixr 5 <|\n", "(<|) :: a -> FingerTree a -> FingerTree a\n", "\n", "-- Base case #1: If this is an empty finger tree, make it one element.\n", "x <| Empty = Single x\n", "\n", "-- Base case #2: For a single tree, upgrade it to a deep one.\n", "-- Remember that the list syntax is actually creating 'Affix a' values.\n", "x <| Single y = Deep [x] Empty [y]\n", "\n", "-- Recursive case: if we have a prefix with four elements, we have to\n", "-- use the last 2 elements with the new one to create a node, and then\n", "-- we prepend that node to the deeper finger tree which contains nodes.\n", "x <| Deep [a, b, c, d] deeper suffix = Deep [x, a] (node <| deeper) suffix\n", " where\n", " node = Branch3 b c d\n", " \n", "-- Non-recursive case: we can just prepend to the prefix.\n", "x <| tree = tree { prefix = affixPrepend x $prefix tree }" ], "language": "python", "metadata": { "hidden": false }, "outputs": [], "prompt_number": 9 }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "We can do the exact same thing for appending on the right, since we have access to the right end of the tree in the same way as the left end:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "infixl 5 |>\n", "(|>) :: FingerTree a -> a -> FingerTree a\n", "Empty |> y = Single y\n", "Single x |> y = Deep [x] Empty [y]\n", "Deep prefix deeper [a, b, c, d] |> y = Deep prefix (deeper |> node) [d, y]\n", " where\n", " node = Branch3 a b c\n", "tree |> y = tree { suffix = affixAppend y$ suffix tree }" ], "language": "python", "metadata": { "hidden": false }, "outputs": [], "prompt_number": 10 }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "We can now construct finger trees easily by appending and pre-pending elements to them:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "empty :: FingerTree a\n", "empty = Empty\n", "\n", "'t' <| empty |> 'x' |> 'y' |> 'z' |> 'w' |> 'm'" ], "language": "python", "metadata": { "hidden": false }, "outputs": [ { "metadata": {}, "output_type": "display_data", "text": [ "Deep {prefix = One 't', deeper = Single (Branch3 'x' 'y' 'z'), suffix = Two 'w' 'm'}" ] } ], "prompt_number": 11 }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "Although we've implemented append and prepend for finger trees, it may seem like we haven't gained much in terms of efficiency over trees, because if we get unlucky and the tree already has a lot of prefixes of length four, we may have to traverse all the way down the tree to add the elements. As a result, the worst case of any prepend or append operation is $O(\\lg n)$, where $n$ is the number of elements in the list. \n", "\n", "While the worst case hasn't gotten better, performance for the typical use case has imporoved. In most uses of prepend and append, the user will be appending or prepending many elements in a row, each time only keeping the new modified tree and discarding the old tree. To analyze this use case, assume that we are performing $m$ append or $m$ prepend operations in a row.\n", "\n", "To analyze the asymptotic runtime of this use case, note first that all the non-recursive branches of append are constant time. If the original tree is small (Empty or Single x), or if we can immediately add the element by modifying the prefix, the append or prepend is takes $O(1)$ time. The recursive case (where the affix has length four) is the problematic one. However, when we encounter an affix of length four and want to add to it, we immediately rebalance the tree such that the affix has length two. Thus, we know *for sure* that the next operation that wants to add an element to that affix can do so immediately in constant time, and will *not* need to descend another level. From this we can deduce that no more than half the operations could possibly need to recurse down into the second layer of the finger tree; for each operation that *does* recurse, there must be *at least* one operation that doesn't. Since the same logic applies to the finger tree at the second layer, we know that only one *quarter* of operations could possibly go down to the third layer. Continuing with the same logic, the $n$th layer of the finger tree could only be visited by one out of every $2^{n-1}$ operations. Thus, the total time $T$ for all $m$ of the append or prepend operations is *at worst* going to be\n", "\n", "$$T = m + \\frac{1}{2}m + \\frac{1}{4}m + \\frac{1}{8}m + \\cdots,$$\n", "\n", "because $m$ operations do something at the first level of the tree, $\\frac{1}{2}m$ operations do something at the second level of the tree, and so on. However, *even* if we assume there are an infinite number of layers (and clearly there are less), this series of terms sums to $2m$ (which you can compute using the formula for the sum of a geometric series). Thus, we take $O(m)$ time for $m$ operations, so while the worst case for a single operations is $O(\\lg n)$ with $n$ elements in the tree, the amortized time for this use case is just $O(1)$ for each prepend or append." ] }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "## Views (First and Last)\n", "\n", "In the previous section, we implemented an append (|>) and a prepend (<|) operation to *add* elements to the start or end of our finger-tree-based sequence. However, in addition to adding elements, we need to be able to look at them and remove them. Both of these operations will be based on a more fundamental view operation, which we implement next.\n", "\n", "The view operation has two versions: a left view viewl and a right view viewr. Each of these takes one element off the end of the finger tree (left and right end, respectively) and returns that element along with a finger tree representing the rest of the elements. To make this clearer, an equivalent of viewl for a list would be" ] }, { "cell_type": "code", "collapsed": false, "input": [ "-- We return our split values wrapped in Maybe,\n", "-- because if the list or finger tree is empty, a split is impossible.\n", "listViewL :: [a] -> Maybe (a, [a])\n", "listViewL [] = Nothing\n", "listViewL (x:xs) = Just (x, xs)" ], "language": "python", "metadata": { "hidden": false }, "outputs": [], "prompt_number": 12 }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "A naive implementation of viewl for finger trees might look as follows:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "-- For convenience and clarity, construct a view data\n", "-- structure instead of using Maybe (a, FingerTree a).\n", "data View a = Nil | View a (FingerTree a)\n", " deriving Show\n", "\n", "viewl :: FingerTree a -> View a\n", "viewl Empty = Nil -- Empty sequences can't be viewed.\n", "viewl (Single x) = View x Empty -- The remainder is empty.\n", "viewl (Deep prefix deeper suffix) = \n", " View first $Deep (fromList rest) deeper suffix\n", " where\n", " -- We know that the prefix has at least one element,\n", " -- so this pattern will always match.\n", " first:rest = toList prefix" ], "language": "python", "metadata": { "hidden": false }, "outputs": [], "prompt_number": 13 }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "We can even test that this implementation works for an empty tree and for the example tree we devised before:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "viewl empty" ], "language": "python", "metadata": { "hidden": false }, "outputs": [ { "metadata": {}, "output_type": "display_data", "text": [ "Nil" ] } ], "prompt_number": 14 }, { "cell_type": "code", "collapsed": false, "input": [ "viewl exampleTree" ], "language": "python", "metadata": { "hidden": false }, "outputs": [ { "metadata": {}, "output_type": "display_data", "text": [ "View 't' (Deep {prefix = One 'h', deeper = Deep {prefix = Two (Branch2 'i' 's') (Branch2 'i' 's'), deeper = Empty, suffix = Two (Branch3 'n' 'o' 't') (Branch2 'a' 't')}, suffix = Three 'r' 'e' 'e'})" ] } ], "prompt_number": 15 }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "While it may seem that it works, this implementation actually has a very serious flaw. Can you spot it?\n", "\n", "The following code block demonstrates this issue:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "let View _ rest = viewl exampleTree\n", "viewl rest" ], "language": "python", "metadata": { "hidden": false }, "outputs": [ { "html": [ "Affix must have one to four elements" ], "metadata": {}, "output_type": "display_data", "text": [ "Affix must have one to four elements" ] } ], "prompt_number": 16 }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "When we wrote the case of viewl that dealt with Deep constructors, we simply took an element off the left prefix. While we know this works and this will indeed yield the first element, the finger tree that contains the rest of the elements *may not be valid*. In the block above, we tried to use viewl to create a finger tree that contained zero elements in its prefix, which of course is illegal and immediately raised an error.\n", "\n", "In order to handle this case, we have to explicitly check for the number of elements in the finger tree prefix. Then, if there is only one element, we cannot remove it; instead, we must use viewl on the deeper finger tree to get a Node a. This Node a will contain two or three more values, so we can remove the single element in the prefix and instead replace the prefix with the contents of the Node a, thus maintaining the invariant that every affix has between one and four elements. The following code implements viewl properly, reusing the same View a data structure from before:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "-- The simple cases are identical to our previous definiton.\n", "viewl :: FingerTree a -> View a\n", "viewl Empty = Nil -- Empty sequences can't be viewed.\n", "viewl (Single x) = View x Empty -- The remainder is empty.\n", "\n", "-- Handling the Deep case is somewhat tricky.\n", "-- When the prefix is has only one element, \n", "-- there are several edge cases we must handle.\n", "viewl (Deep [x] deeper suffix) = View x rest\n", " where\n", " rest =\n", " -- Compute what the remainder of the finger tree is.\n", " case viewl deeper of\n", " -- If we can get a node from the deeper finger tree...\n", " View node rest' ->\n", " -- Promote the node to the prefix.\n", " Deep (fromList$ toList node) rest' suffix\n", " \n", " -- If there are no more nodes in the deeper finger tree,\n", " -- the remainder is the elements of the suffix.\n", " -- We must restructure them into a finger tree.\n", " Nil -> case suffix of\n", " [x] -> Single x\n", " [x, y] -> Deep [x] Empty [y]\n", " \n", " -- In the next two cases, the choice to put all but\n", " -- one element on the left is arbitrary. The only\n", " -- constraint is that each side have at least one element.\n", " [x, y, z] -> Deep [x, y] Empty [z]\n", " [x, y, z, w] -> Deep [x, y, z] Empty [w]\n", " \n", "-- Finally, we have the simple Deep case, where \n", "-- we can just chop an element off the prefix.\n", "viewl (Deep prefix deeper suffix) =\n", " View first $Deep (fromList rest) deeper suffix\n", " where\n", " first:rest = toList prefix" ], "language": "python", "metadata": { "hidden": false }, "outputs": [], "prompt_number": 17 }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "With this new implementation of viewl, our failing test from before works fine:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "let View _ rest = viewl exampleTree\n", "viewl rest" ], "language": "python", "metadata": { "hidden": false }, "outputs": [ { "metadata": {}, "output_type": "display_data", "text": [ "View 'h' (Deep {prefix = Two 'i' 's', deeper = Deep {prefix = One (Branch2 'i' 's'), deeper = Empty, suffix = Two (Branch3 'n' 'o' 't') (Branch2 'a' 't')}, suffix = Three 'r' 'e' 'e'})" ] } ], "prompt_number": 18 }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "The right equivalent of viewl, viewr, is implemented in almost exactly the same way, substituting uses of the prefix for the suffix and vice versa:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "viewr :: FingerTree a -> View a\n", "viewr Empty = Nil\n", "viewr (Single x) = View x Empty\n", "viewr (Deep prefix deeper [x]) = View x rest\n", " where\n", " rest =\n", " case viewr deeper of\n", " -- Promote a node to the suffix if we can.\n", " View node rest' ->\n", " Deep prefix rest' (fromList$ toList node)\n", " \n", " -- Convert the prefix to a tree if no more nodes\n", " -- exist in the deeper finger tree.\n", " Nil -> case prefix of\n", " [x] -> Single x\n", " [x, y] -> Deep [x] Empty [y]\n", " [x, y, z] -> Deep [x] Empty [y, z]\n", " [x, y, z, w] -> Deep [x] Empty [y, z, w]\n", "viewr (Deep prefix deeper suffix) =\n", " View suffixLast $Deep prefix deeper (fromList suffixInit)\n", " where\n", " suffixLast = last$ toList suffix\n", " suffixInit = init $toList suffix" ], "language": "python", "metadata": { "hidden": false }, "outputs": [], "prompt_number": 19 }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "We use it just like we use viewl, and it gives us access to the end of the sequence:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "viewr exampleTree" ], "language": "python", "metadata": { "hidden": false }, "outputs": [ { "metadata": {}, "output_type": "display_data", "text": [ "View 'e' (Deep {prefix = Two 't' 'h', deeper = Deep {prefix = Two (Branch2 'i' 's') (Branch2 'i' 's'), deeper = Empty, suffix = Two (Branch3 'n' 'o' 't') (Branch2 'a' 't')}, suffix = Two 'r' 'e'})" ] } ], "prompt_number": 20 }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "Since we now have our view primitives, we can easily implement a few other functions, such as the finger tree equivalents of head, tail, last, init, and null:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "treeHead :: FingerTree a -> a\n", "treeHead tree = case viewl tree of\n", " Nil -> error \"no elements in tree\"\n", " View x _ -> x\n", " \n", "treeTail :: FingerTree a -> FingerTree a\n", "treeTail tree = case viewl tree of\n", " Nil -> error \"no elements in tree\"\n", " View _ xs -> xs\n", "\n", "treeLast :: FingerTree a -> a\n", "treeLast tree = case viewr tree of\n", " Nil -> error \"no elements in tree\"\n", " View x _ -> x\n", " \n", "treeInit :: FingerTree a -> FingerTree a\n", "treeInit tree = case viewr tree of\n", " Nil -> error \"no elements in tree\"\n", " View _ xs -> xs\n", " \n", "isEmpty :: FingerTree a -> Bool\n", "isEmpty tree = case viewl tree of\n", " Nil -> True\n", " _ -> False" ], "language": "python", "metadata": { "hidden": false }, "outputs": [], "prompt_number": 21 }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "In particular, we can now easily convert between lists and finger trees:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "-- Let affixes be treated as lists.\n", "instance IsList (FingerTree a) where\n", " type Item (FingerTree a) = a\n", " \n", " toList tree = case viewl tree of\n", " Nil -> []\n", " View x xs -> x : toList xs\n", "\n", " fromList = foldr (<|) Empty" ], "language": "python", "metadata": { "hidden": false }, "outputs": [], "prompt_number": 22 }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "Using finger trees is now even simpler:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "[1..6] :: FingerTree Int" ], "language": "python", "metadata": { "hidden": false }, "outputs": [ { "metadata": {}, "output_type": "display_data", "text": [ "Deep {prefix = Two 1 2, deeper = Single (Branch3 3 4 5), suffix = One 6}" ] } ], "prompt_number": 23 }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "## Concatenation\n", "\n", "Another operation we can easily implement using the finger tree data structure is concatenation. The operations we currently have are enough to implement simple concatenation, since we can recursively view and then append elements. A very simple implementation of concatentation follows:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "-- Concatenation is done using infix >< operator.\n", "(><) :: FingerTree a -> FingerTree a -> FingerTree a\n", "left >< Empty = left\n", "left >< right =\n", " let View first rest = viewl right in\n", " (left |> first) >< rest" ], "language": "python", "metadata": { "hidden": false }, "outputs": [], "prompt_number": 24 }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "Although this implementation works fine (as you can verify by looking at the value of something like exampleTree >< exampleTree), it's fairly slow. In terms of asymptotic runtime, it's the same as using toList to get a list of the finger tree elements, concatenating the lists, and then using fromList to convert back to a finger tree. We've shown that |> takes amortized$O(1)$time, but we must do that$O(m)$times, where$m$is the number of elements in the right tree passed to ><. Thus, the total running time is$O(m)$\u2013 it's linear in the number of elements we're appending.\n", "\n", "It turns out we can do much better by utilizing the structure of the finger tree. Before doing this, though, we're going to need a helper function called nodes, which can convert from a list of items to a list of Nodes of items:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "nodes :: [a] -> [Node a]\n", "nodes xs = case xs of\n", " [] -> error \"not enough elements for nodes\"\n", " [x] -> error \"not enough elements for nodes\"\n", " [x, y] -> [Branch2 x y]\n", " [x, y, z] -> [Branch3 x y z]\n", " x:y:rest -> Branch2 x y : nodes rest" ], "language": "python", "metadata": { "hidden": false }, "outputs": [], "prompt_number": 25 }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "For every two elements in the original list, nodes will output only one element in the new list of nodes. In order to accommodate odd numbers of elements, nodes will emit a Branch3 when it is left with a triple. As a result, we know for sure that if nodes is given a list of$n$elements, it will emit a list of$\\lfloor \\frac{n}{2} \\rfloor$nodes. This will be important later on.\n", "\n", "Next, we're going to redefine concatenation in terms of a somewhat strange operator we'll call concatWithMiddle. concatWithMiddle takes two FingerTree a values to concat, as well as a list of elements to stick between the two trees. Implementing >< with concatWithMiddle is trivial \u2013 we just pass an empty list as the extra elements:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "(><) :: FingerTree a -> FingerTree a -> FingerTree a\n", "left >< right = concatWithMiddle left [] right\n", "\n", "concatWithMiddle :: FingerTree a -> [a] -> FingerTree a -> FingerTree a\n", "concatWithMiddle = unimplemented\n", " where unimplemented = error \"Soon to come!\"" ], "language": "python", "metadata": { "hidden": false }, "outputs": [], "prompt_number": 26 }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "The only thing remaining to implement is concatWithMiddle. We need a few special cases to deal with the Empty and Single constructors; in these cases, concatenation simply reduces to$O(1)$appends. We handle the list of extra elements in the middle by also using several appends or prepends.\n", "\n", "In addition to the edge cases, we must handle the common case in which both trees are created with the Deep constructor. When this is the case, we also return a Deep constructor with:\n", "\n", "- prefix equal to the prefix of the left tree\n", "- suffix equal to the suffix of the right tree\n", "- deeper (the next finger tree) equal to a recursive call to concatWithMiddle\n", "\n", "We also must handle the suffix of the left tree and prefix of the right tree. These can be combined with the middle elements and passed to concatWithMiddle. Since the deeper finger tree stores Node a values instead of a values, we use our helper function nodes to create a list of Nodes we can pass to the recursive concatWithMiddle call. This may be somewhat confusing, and should be elucidated by reading the code:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "concatWithMiddle :: FingerTree a -> [a] -> FingerTree a -> FingerTree a\n", "\n", "-- Base cases: just use prepending or appending.\n", "concatWithMiddle Empty [] right = right\n", "concatWithMiddle Empty (x:xs) right = x <| concatWithMiddle Empty xs right\n", "concatWithMiddle (Single y) xs right = y <| concatWithMiddle Empty xs right\n", "\n", "concatWithMiddle left [] Empty = left\n", "concatWithMiddle left xs Empty = concatWithMiddle left (init xs) Empty |> last xs\n", "concatWithMiddle left xs (Single y) = concatWithMiddle left xs Empty |> y\n", "\n", "-- Recursive case: both trees are deep.\n", "concatWithMiddle left mid right = \n", " Deep (prefix left) deeper' (suffix right)\n", " where\n", " -- Use concatWithMiddle recursively to generate the next level.\n", " deeper' = concatWithMiddle (deeper left) mid' (deeper right)\n", " \n", " -- Get a list of elements in the left suffix, provided middle, and right prefix.\n", " -- Convert these into nodes before passing them to concatWithMiddle.\n", " mid' = nodes$ (toList $suffix left) ++ mid ++ (toList$ prefix right)\n", "\n", "-- Use >< for more convenient concatenation.\n", "(><) :: FingerTree a -> FingerTree a -> FingerTree a\n", "left >< right = concatWithMiddle left [] right" ], "language": "python", "metadata": { "hidden": false }, "outputs": [], "prompt_number": 27 }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "We can test that this code works as we did before, by looking at the output of something like exampleTree >< exampleTree:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "putStrLn $toList$ exampleTree >< exampleTree\n", "putStrLn $toList$ concatWithMiddle exampleTree \" \" exampleTree" ], "language": "python", "metadata": { "hidden": false }, "outputs": [ { "metadata": {}, "output_type": "display_data", "text": [ "thisisnotatreethisisnotatree" ] }, { "metadata": {}, "output_type": "display_data", "text": [ "thisisnotatree thisisnotatree" ] } ], "prompt_number": 28 }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "While it's clear that this code is functional (no pun intended), it's not clear that we've actually done any better in terms of asymptotic runtime guarantees. If we look at the base case for concatWithMiddle, we're still doing a ton of prepends! Since every time we recurse down another layer, we add elements to the middle list (from the unused affixes), is it possible that we still have something like $O(m)$ prepends done in the base cases?\n", "\n", "Surprisingly enough, the answer to this is **no**. We can prove that the base cases *still* take only $O(1)$ amortized time. The magic here lies in our use of nodes. As we showed when we defined nodes, nodes is *guaranteed* to output a list no more than half the length of the input list. Using this property, we can easily track the maximum length that the middle list can be at any point in the computation.\n", "\n", "When the computation starts, we know that the middle list has length zero, since we pass concatWithMiddle an empty list in our definition of ><. At each step, we add two affixes (a suffix and a prefix) to the middle list before applying nodes to it. We know that the affixes have no more than four elements, so we are adding *at most* eight elements to the middle list. As a result, after we apply nodes, our list can have no more than eight elements, because as we add more and more elements, the length of the output of nodes can get closer and closer to eight; however, it *cannot* go above eight, because if we start out with less than or equal to eight elements, add eight elements, then divide the length by two, we will end up with less than or equal to eight elements again. To convince yourself, you can trace through an example execution in which you start with zero elements and add eight at each recursive step:\n", "\n", "- Step 0: Middle list has 0 elements. \n", "- Step 1: Add 8 elements (4 from suffix, 4 from prefix). nodes reduces the length by half, so middle list now has 4 elements.\n", "- Step 2: Add 8 elements, for a total of 12; nodes reduces length to 6.\n", "- Step 3: Add 8 elements, for a total of 14; nodes reduces length to 7.\n", "- Step 4: Add 8 elements, for a total of 15; nodes reduces length to 7.\n", "\n", "Note how the last two steps both yielded a list of the same size \u2013 once the computation reaches that point, the middle list will not become any longer as the recursion continues. Thus, the length of the middle list is bounded by seven, which is $O(1)$ (a constant); as a result, we can confidently say that all of the base cases are also $O(1)$ amortized running time, because they do no more than eight prepends.\n", "\n", "Since the base cases are all constant time, the main contributor to the runtime of our >< is the recursion. At each recursive step, we look at the deeper tree in both the left and right trees passed to concatWithMiddle; we reach a base case as soon as one of these trees is not created with the Deeper constructor. The depth of these trees grows logarithmically with the number of elements in them; if the finger tree has $n$ elements, it's depth is $O(\\lg n)$. Since our runtime is proportional to the *minimum* depth of either tree, our asympotic runtime bounds are $O(\\min(\\lg n, \\lg m)) = O(\\lg(\\min(m, n)))$, where $n$ and $m$ are the number of elements in the left and right trees, respectively." ] }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "# Applications of Finger Trees" ] }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "We've described the finger tree data structure and figured out how to use it as a sequence, at least as far as access to the front and back of the sequence are concerned. However, we have yet to figure out how to access *any* element of the sequence without traversing a ton of elements to get to it.\n", "\n", "Instead of just defining a random access primitive that operates on finger trees, we will instead define a more general search operation. We'll then use our general search operation to implement random access sequences and prioritiy queues, both based on finger trees.\n", "\n", "To implement our search operation, we will need each node of the finger tree to be marked with an annotation. To that end, we begin by redefining our finger tree data structures to store annotations at each branch:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "-- 'v' is the type of the annotation.\n", "data Node v a = Branch3 v a a a\n", " | Branch2 v a a\n", " deriving Show\n", " \n", "data FingerTree v a \n", " = Empty\n", " | Single a\n", " | Deep {\n", " annotation :: v, -- Add an annotation to each branch.\n", " prefix :: Affix a,\n", " deeper :: FingerTree v (Node v a),\n", " suffix :: Affix a\n", " }\n", " deriving Show" ], "language": "python", "metadata": { "hidden": false }, "outputs": [], "prompt_number": 29 }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "We require that these annotations are *monoidal*; that is, that the type v is a member of the Monoid typeclass. Recall that a monoid is something that has an associative append operation (<>) with an identity (empty). This is embodied in the following typeclass, which is slightly different from the Monoid typeclass that ships in the Haskell base library:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "class Monoid m where\n", " -- Called 'mempty' in the Haskell base library.\n", " empty :: m\n", " \n", " -- Called 'mappend' in the Haskell base library.\n", " (<>) :: m -> m -> m" ], "language": "python", "metadata": { "hidden": false }, "outputs": [], "prompt_number": 30 }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "We also require that the annotations are not arbitrary annotations, but are actually related to the values in the tree. The annotations must be *measures* of elements of the tree. More precisely, there must be a measure function that accepts an element of the tree and outputs an annotation for that element. To create that function, we must implement the following Measured typeclass for our element type and annotation type:" ] }, { "cell_type": "code", "collapsed": false, "input": [ ":set -XMultiParamTypeClasses\n", "\n", "-- The output of the measure must be a monoid.\n", "class Monoid v => Measured a v where\n", " measure :: a -> v" ], "language": "python", "metadata": { "hidden": false }, "outputs": [], "prompt_number": 31 }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "We can implement a measure for all the data types used in our finger tree \u2013 FingerTree, Node, and Affix. For FingerTree's Deep constructor and Node, we cache the annotations, so we just need to retrieve them when we implement measure. For the Empty and Single constructors, we must use the identity element empty and the measure function:" ] }, { "cell_type": "code", "collapsed": false, "input": [ ":set -XFlexibleInstances\n", "\n", "instance Measured a v => Measured (FingerTree v a) v where\n", " measure Empty = empty\n", " measure (Single x) = measure x\n", " measure tree = annotation tree\n", "\n", "instance Measured a v => Measured (Node v a) v where\n", " measure (Branch2 v _ _) = v\n", " measure (Branch3 v _ _ _) = v" ], "language": "python", "metadata": { "hidden": false }, "outputs": [], "prompt_number": 32 }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "For Affix, we have chosen (somewhat arbitrarily) to not cache the annotations in the Affix data structure, so instead our implementation of measure computes it from the values in the affix:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "-- Called 'mconcat' in the Haskell prelude.\n", "concat :: Monoid m => [m] -> m\n", "concat = foldr (<>) empty\n", "\n", "instance Measured a v => Measured (Affix a) v where\n", " measure = concat . map measure . toList" ], "language": "python", "metadata": { "hidden": false }, "outputs": [], "prompt_number": 33 }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "The definition above is why we require that annotations be a monoid. Since the annotations form a monoid, we can easily compute annotations for branches and affixes based on the measures of the values they contain. The measure of a branch or an affix is the monoidal sum (concat) of all the measures of the values they contain. \n", "\n", "In order to simplify our lives, we also need to provide convenience constructors for our new Node constructors and the Deep constructor. First, we implement the IsList typeclass for Node values, so we can easily create new nodes without worrying about annotations:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "-- Our IsList instance allows us to write [x, y] to create an annotated node.\n", "instance Measured a v => IsList (Node v a) where\n", " type Item (Node v a) = a\n", " \n", " toList (Branch2 _ x y) = [x, y]\n", " toList (Branch3 _ x y z) = [x, y, z]\n", " \n", " fromList [x, y] = \n", " Branch2 (measure x <> measure y) x y\n", " fromList [x, y, z] = \n", " Branch3 (measure x <> measure y <> measure z) x y z\n", " fromList _ = error \"Node must contain two or three elements\"\n", " " ], "language": "python", "metadata": { "hidden": false }, "outputs": [], "prompt_number": 34 }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "Next, we provide a convenience constructor for trees made with the Deep constructor. This constructor takes care of setting the annotation, and thus has a Measured constraint. However, this constructor also differs from Deep in that it allows the prefixes to be empty, which will greatly simplify our code later. In order to use the constructor, we're going to have to change a lot of our older code to handle the new FingerTree v a type; in the following code block, pay attention to deep and the functions that it uses, but ignore the reimplementations of View, viewr, and viewl \u2013 they are just the same code you saw earlier with a little bit more logic to handle the annotations:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "-- Convert an affix into an entire tree, doing rebalancing if necessary.\n", "affixToTree :: Measured a v => Affix a -> FingerTree v a\n", "affixToTree affix = case affix of\n", " [x] -> Single x\n", " [x, y] -> Deep (measure affix) [x] Empty [y]\n", " [x, y, z] -> Deep (measure affix) [x] Empty [y, z]\n", " [x, y, z, w] -> Deep (measure affix) [x, y] Empty [z, w]\n", " \n", "-- The deep function creates Deep finger trees.\n", "deep :: Measured a v => [a] -> FingerTree v (Node v a) -> [a] -> FingerTree v a\n", "deep prefix deeper suffix = case (prefix, suffix) of\n", " ([], []) -> case viewl deeper of\n", " Nil -> Empty\n", " View node deeper' -> deep (toList node) deeper' []\n", " ([], _) -> case viewr deeper of\n", " Nil -> affixToTree $fromList suffix\n", " View node deeper' -> deep (toList node) deeper' suffix\n", " (_, []) -> case viewr deeper of\n", " Nil -> affixToTree$ fromList prefix\n", " View node deeper' -> deep prefix deeper' (toList node)\n", " \n", " _ -> if length prefix > 4 || length suffix > 4\n", " then error \"Affixes cannot be longer than 4 elements\"\n", " else Deep annotation (fromList prefix) deeper (fromList suffix)\n", " where\n", " annotation = concat (map measure prefix) <> measure deeper <> concat (map measure suffix)\n", "\n", "-- We must redefine viewl and viewr, since we have changed our FingerTree data type.\n", "-- All that follows you have already seen \u2013 it is simply shorter and less well-commented.\n", "data View v a = Nil | View a (FingerTree v a) deriving Show\n", " \n", "viewr :: Measured a v => FingerTree v a -> View v a\n", "viewr Empty = Nil\n", "viewr (Single x) = View x Empty\n", "viewr (Deep _ prefix deeper [x]) = View x $\n", " case viewr deeper of\n", " View node rest' ->\n", " let suff = fromList$ toList node\n", " annot = measure prefix <> measure rest' <> measure suff in\n", " Deep annot prefix rest' suff\n", " Nil -> affixToTree prefix\n", "viewr (Deep _ prefix deeper suffix) =\n", " View suffixLast $Deep annot prefix deeper suffixInit\n", " where\n", " annot = measure prefix <> measure deeper <> measure suffixInit\n", " suffixLast = last$ toList suffix\n", " suffixInit = fromList $init$ toList suffix\n", " \n", "viewl :: Measured a v => FingerTree v a -> View v a\n", "viewl Empty = Nil\n", "viewl (Single x) = View x Empty\n", "viewl (Deep _ [x] deeper suffix) = View x $case viewl deeper of\n", " View node rest' ->\n", " let pref = fromList$ toList node\n", " annot = measure pref <> measure rest' <> measure suffix in\n", " Deep annot pref rest' suffix\n", " Nil -> affixToTree suffix\n", "viewl (Deep _ prefix deeper suffix) =\n", " View first $Deep annot prefix' deeper suffix\n", " where\n", " first:rest = toList prefix\n", " prefix' = fromList rest\n", " annot = measure prefix' <> measure deeper <> measure suffix" ], "language": "python", "metadata": { "hidden": false }, "outputs": [], "prompt_number": 35 }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "We've gone through a whole lot of setup without anything interesting; however, at this point, we're finally prepared to work on our search algorithm, which we will later use to implement random access into our finger trees (as well as other things). Our search will accept a predicate (v -> Bool) that operates on our monoidal annotations (v). The predicate (let's call it pred) must satisfy a few properties:\n", "\n", "- pred empty == False: The predicate must return False on the monoidal identity element.\n", "- If pred x == True, then pred (x <> y) must also be True, regardless of y. This means that pred is monotonically increasing, and adding more elements to the monoidal sum must not make it false.\n", "\n", "The search will scan through our finger tree, adding up the annotations of all the elements as it goes. It will check whether each of the sums satisfies our predicate pred. The search will find and return the location in the finger tree sequence where pred switches from being False to True; if no such place exists, the search will fail.\n", "\n", "The goal of our search is depicted in the following graphic from the paper by Hinze and Patterson:\n", " \n", "\n", "In the graphic above,$v_x$is the sum of annotations for elements$0$through$x$, which is why the$v_x$values appear on the space *between* the elements. The very first value,$v_0$, is the monoidal identity element empty, depicted there as$i$. The search locates the element$x_i$such that pred applied to$v_{i-1}$is False and pred applied to$v_i$is True.\n", "\n", "For example, the following function splitList implements this search algorithm on simple lists, returning a tuple where the first element contains$x_0$through$x_{i-1}$, and the second element contains$x_i$and all later elements:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "splitList :: Measured a v \n", " => (v -> Bool) -- Monotonic predicate on annotations.\n", " -> v -- Left-most annotation.\n", " -> [a] -- List of measurable values.\n", " -> ([a], [a])\n", "splitList pred start [] = error \"Split point not found\"\n", "splitList pred start (x:xs)\n", " -- Base case of recursion: we found the split point.\n", " | pred start' = ([], x:xs)\n", " \n", " -- If not a split point, keep looking...\n", " | otherwise =\n", " let (before, after) = splitList pred start' xs in\n", " (x : before, after)\n", " where\n", " -- The new left-most annotation value after including this element.\n", " start' = start <> measure x" ], "language": "python", "metadata": { "hidden": false }, "outputs": [], "prompt_number": 36 }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "For lists, the implementation of splitList is fairly straightforward. The implementation for finger trees, which we will call split, shares the same idea, but ends up being somewhat more convoluted to implement. We define a custom Split data structure to store the split location that our search found; our upcoming split function will return a Split as its result. In this Split data structure, the left and right parts of the sequence are stored as finger trees, and the element$x_i$(which caused pred to switch) is stored directly:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "data Split v a = Split (FingerTree v a) a (FingerTree v a) deriving Show" ], "language": "python", "metadata": { "hidden": false }, "outputs": [], "prompt_number": 37 }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "Finally, we can implement split. split is the workhorse of our search. Given a subsequence (passed in as a FingerTree v a) and the annotation at the start of the subsequence, split returns a Split indicating where the predicate switches. Of course, split assumes that the predicate applied to the left value is False \u2013 if not, then the search is pointless, as the predicate should return true for all points in the subsequence." ] }, { "cell_type": "code", "collapsed": false, "input": [ "split :: Measured a v \n", " => (v -> Bool) -- Monotonic predicate on annotations.\n", " -> v -- Annotation on the left end of the subsequence.\n", " -> FingerTree v a -- Subsequence to search within.\n", " -> Split v a\n", "\n", "-- An empty finger tree cannot have a split, since there\n", "-- are no elements whose annotations we \n", "-- can add to the monoidal value we are given.\n", "split _ _ Empty = error \"Split point not found\"\n", "\n", "-- For a single element, we must check whether or not its\n", "-- annotation makes the predicate true.\n", "split pred start (Single x)\n", " | pred (start <> measure x) = Split Empty x Empty\n", " | otherwise = error \"Split point not found\"\n", " \n", "-- For the deeper case, we must do several checks:\n", "-- Up to one for each prefix and for the deeper tree.\n", "split pred start (Deep total pref deeper suff)\n", " -- Make sure a split point exists.\n", " | not (pred$ start <> total) = error \"Split point not found\"\n", " \n", " -- The split point is in the prefix.\n", " | pred startPref = \n", " -- Treat the prefix as a list and find where the split point is.\n", " let (before, x:after) = splitList pred start prefix in\n", " -- Convert the pre-split part of the prefix to a tree.\n", " Split (chunkToTree before) x (deep after deeper suffix)\n", " \n", " -- The split point is in the deeper tree.\n", " | pred (start <> measure pref <> measure deeper) =\n", " -- Find the split point in the deeper tree.\n", " -- The split point is not as fine-grained as we want, as it works on Node v a,\n", " -- instead of just values of type a.\n", " let Split before node after = split pred startPref deeper\n", " start' = start <> measure pref <> measure before\n", " \n", " -- Convert the node at the split point into a list, and search for the\n", " -- real split point within that list.\n", " (beforeNode, x:afterNode) = splitList pred start' $toList node in\n", " \n", " -- Finally, combine all the pieces back into two trees.\n", " Split (deep prefix before beforeNode) x (deep afterNode after suffix)\n", " \n", " -- Otherwise, the split point is in the suffix.\n", " | otherwise = \n", " let start' = startPref <> measure deeper\n", " (before, x:after) = splitList pred start' suffix in\n", " -- Recall that the deep constructor was designed to handle\n", " -- potentially empty affixes, and takes lists as arguments.\n", " Split (deep prefix deeper before) x (chunkToTree after)\n", " \n", " where\n", " -- Convert the Affix a into [a], so we can use splitList.\n", " prefix = toList pref\n", " suffix = toList suff\n", " \n", " startPref = start <> measure pref\n", " \n", " -- Convert a small list into a tree.\n", " chunkToTree [] = Empty\n", " chunkToTree xs = affixToTree$ fromList xs" ], "language": "python", "metadata": { "hidden": false }, "outputs": [], "prompt_number": 38 }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "If you look carefully at the definition of split, you'll note that it does a constant amount of work at each step. (splitList is a constant amount of work, because we only pass it lists made of nodes and affixes, which cannot exceed four elements in size.) Each step also recurses deeper if it needs to (if the split is in the deeper tree and not in an affix). Thus, in the worst case, we'll do $O(1)$ work for each of the layers of the finger tree; since there are $O(\\lg n)$ layers in the finger tree, the split operation has worst case runtime bounds of $O(\\lg n)$.\n", "\n", "With that, we've completed split and implemented the bulk of the functionality necessary to use finger trees as random access sequences. In the next section, we'll look at exactly how we can use these monoidal annotations to do random access." ] }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "### Random-Access Sequences" ] }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "We're prepared to get to the meat of our random access algorithm. In order to implement random-access trees, we're going to annotate each subtree with the number of elements it contains. To achieve this, we just need to annotate each leaf with the value 1 and use summation as monoidal addition. Since our finger trees automatically take care of their own annotations, all we need to do is specify the types the finger tree stores, the measure of those types, and how to combine subtree sizes (just addition):" ] }, { "cell_type": "code", "collapsed": false, "input": [ ":set -XGeneralizedNewtypeDeriving\n", "\n", "-- Monoidal size \u2013 all leaves have Size 1.\n", "newtype Size = Size Int deriving (Show, Eq, Ord)\n", "\n", "-- Storage for our values.\n", "newtype Value a = Value a deriving Show\n", "\n", "-- Sizes just add normally.\n", "instance Monoid Size where\n", " empty = Size 0\n", " Size x <> Size y = Size $x + y\n", " \n", "-- All values just have size one.\n", "instance Measured (Value a) Size where\n", " measure _ = Size 1" ], "language": "python", "metadata": { "hidden": false }, "outputs": [], "prompt_number": 39 }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "Using the types and instances above, leaves of our finger tree are annotated with the value one. Intermediate nodes are annotated with the size of their subtree. In order to find the$n$th node in our sequence, we can look for the place where the sum of the annotations becomes *greater* than$n$. For example, if we search for the place where the annotations become greater than five, the split point we find will be at the sixth element, because the sixth element is what makes the annotations become greater than five. In a zero-indexed sequence, five is indeed the index of the sixth element!\n", "\n", "Thus, the implementation of random access sequences requires a very simple (!) operator, which is just a thin wrapper around split:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "-- A wrapper around our finger tree which hides the fact that\n", "-- we're using Size and Value to guide typeclass inference.\n", "newtype Seq a = Seq (FingerTree Size (Value a))\n", "\n", "-- Random-access indexing.\n", "(!) :: Seq a -> Int -> a\n", "Seq tree ! idx = val\n", " where\n", " -- We unwrap the Split and the Value to get the actual\n", " -- value at the index we're accessing.\n", " Split _ (Value val) _ = split (> Size idx) (Size 0) tree" ], "language": "python", "metadata": { "hidden": false }, "outputs": [], "prompt_number": 40 }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "Let's create an example sequence to test our algorithm on:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "layer3 :: FingerTree v a\n", "layer3 = Empty\n", "\n", "mkBranch :: [a] -> Node Size (Value a)\n", "mkBranch = fromList . map Value\n", "\n", "layer2 :: FingerTree Size (Node Size (Value Char))\n", "layer2 = deep prefix layer3 suffix\n", " where\n", " prefix = [mkBranch \"is\", mkBranch \"is\"]\n", " suffix = [mkBranch \"not\", mkBranch \"at\"]\n", "\n", "layer1 :: FingerTree Size (Value Char)\n", "layer1 = deep prefix layer2 suffix\n", " where\n", " prefix = [Value 't', Value 'h']\n", " suffix = [Value 'r', Value 'e', Value 'e']\n", "\n", "exampleSeq :: Seq Char\n", "exampleSeq = Seq layer1" ], "language": "python", "metadata": { "hidden": false }, "outputs": [], "prompt_number": 41 }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "We can test our indexing works by attempting to index into the sequence using each of the possible indices. We should recover the list of elements in the tree:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "print$ map (exampleSeq !) [0..13]" ], "language": "python", "metadata": { "hidden": false }, "outputs": [ { "metadata": {}, "output_type": "display_data", "text": [ "\"thisisnotatree\"" ] } ], "prompt_number": 42 }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "To use this in a serious library, you would want to wrap this in another layer which checks that the index is non-negative and in bounds, and only perform the search if it is, return a Nothing on failure and a Just result on success. In the current implementation, we ignore failure, and if we try to access an element that doesn't exist, the search crashes with an exception that would be rather confusing to the end user:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "exampleSeq ! 14" ], "language": "python", "metadata": { "hidden": false }, "outputs": [ { "html": [ "Split point not found" ], "metadata": {}, "output_type": "display_data", "text": [ "Split point not found" ] } ], "prompt_number": 43 }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "### Priority Queues\n", "\n", "In addition to random-access sequences, we can easily use the same data structure and the same search algorithm for implementing efficient functional priority queues. We will assume that a priority queue is a data structure PriorityQueue a with the two functions push :: PriorityQueue a -> a -> Int -> PriorityQueue a (which pushes a value of a given integer priority onto the queue) and pop :: PriorityQueue a -> (a, PriorityQueue a) (which takes the maximum priority element, removes it from the priority queue, and returns a tuple with the element and the new tree).\n", "\n", "In order to implement our priority queue, we must just choose a different monoid. Instead of our finger trees storing Values and being annotated with Sizes, they will store Prioritized items and be annotated with Prioritys:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "-- The finger tree will store items along with their priorities.\n", "data Prioritized a = Prioritized {\n", " priority :: Int,\n", " item :: a\n", " }\n", "\n", "-- In order for priorities to be a monoid, it must have\n", "-- an identity element. For that we use NegativeInfinity.\n", "data Priority = NegativeInfinity | Priority Int deriving Eq" ], "language": "python", "metadata": { "hidden": false }, "outputs": [], "prompt_number": 44 }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "We must then implement the Measured typeclass, which in turn requires us to implement Monoid for our Priority type. As we will see, our monoid cannot operate on integers alone \u2013 it will need a minimum priority, which we call NegativeInfinity:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "-- Return the maximum of two priorities.\n", "-- NegativeInfinity has lower priority than anything else.\n", "maxPriority NegativeInfinity x = x\n", "maxPriority x NegativeInfinity = x\n", "maxPriority (Priority x) (Priority y) = Priority $max x y\n", "\n", "instance Monoid Priority where\n", " -- Priority is a monoid, where we combine priorities\n", " -- by taking the maximum of them.\n", " (<>) = maxPriority\n", "\n", " -- Since NegativeInfinity combined with any value x\n", " -- is just x, NegativeInfinity is the identity.\n", " empty = NegativeInfinity" ], "language": "python", "metadata": { "hidden": false }, "outputs": [], "prompt_number": 45 }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "As with our random-access sequences, the Measured typeclass is pretty simple to implement. In this case, the measure of any Prioritized item is simply a Priority representing its priority:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "instance Measured (Prioritized a) Priority where\n", " measure = Priority . priority" ], "language": "python", "metadata": { "hidden": false }, "outputs": [], "prompt_number": 46 }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "With these instances, we can define a priority queue data structure as a finger tree:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "newtype PriorityQueue a = PriorityQueue (FingerTree Priority (Prioritized a))" ], "language": "python", "metadata": { "hidden": false }, "outputs": [], "prompt_number": 47 }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "Implementing push is easy: just add an element to the sequence. It doesn't matter how you add it, so we'll just use a prepend:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "push :: PriorityQueue a -> a -> Int -> PriorityQueue a\n", "push (PriorityQueue tree) x priority = \n", " PriorityQueue$ Prioritized priority x <| tree\n", " \n", "-- We need to redefine <| to operate on our new annotated finger trees.\n", "(<|) :: Measured a v => a -> FingerTree v a -> FingerTree v a\n", "x <| Empty = Single x\n", "x <| Single y = deep [x] Empty [y]\n", "x <| Deep annot prefix deeper suffix = case prefix of\n", " [a, b, c, d] -> Deep annot' [x, a] ([b, c, d] <| deeper) suffix\n", " prefix -> Deep annot' (affixPrepend x prefix) deeper suffix\n", " where\n", " annot' = measure x <> annot" ], "language": "python", "metadata": { "hidden": false }, "outputs": [], "prompt_number": 48 }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "In order to implement pop, we'll need to use our Monoid instance, along with our split routine. Since our monoid instance combines priorities by choosing the largest one, each subtree will be annotated with the largest priority it contains. Thus, to find the maximum priority p in the entire tree, we can just measure the tree itself, since it will be annotated with the largest priority it contains. Then, to find an item of a priority p, we can just search for where the predicate == Priority p becomes true.\n", "\n", "Recall that we had two requirements on our predicate: first, it must be false on our identity element empty, and second, it must be monotonic \u2013 once it is satisfied, it will remain satisfied if we add in all the other elements of the sequence. Both of these properties hold in this case. Since empty is defined to be NegativeInfinity, we know that checking for equality with some priority will return false. The second property is true by virtue of the fact that the priority we're searching for, p, is known to be the maximum priority that exists in the tree; thus, no matter how many elements we add to the monoidal sum, we know the result will just be Priority p, because the monoidal sum picks out the largest priority (which we know is p).\n", "\n", "Thus, we can implement pop as follows:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "pop :: PriorityQueue a -> (a, PriorityQueue a)\n", "pop (PriorityQueue queue) = (element, PriorityQueue queue')\n", " where\n", " -- Find the maximum priority in the entire tree.\n", " maxPriority = measure queue\n", " \n", " -- Split the tree (find the max priority element).\n", " result = split (== maxPriority) empty queue\n", " \n", " -- Pick out the element from the split. Discard\n", " -- its priority, we only care about its value.\n", " Split left (Prioritized _ element) right = result\n", " \n", " -- Combine the elements we didn't use back into a tree.\n", " queue' = left >< right\n", " \n", "-- We must reimplement >< with our new annotated finger trees.\n", "-- For brevity, we use an inefficient concatenation function.\n", "(><) :: Measured a v => FingerTree v a -> FingerTree v a -> FingerTree v a\n", "left >< right = case viewr left of\n", " Nil -> right\n", " View x left' -> left' >< (x <| right)" ], "language": "python", "metadata": { "hidden": false }, "outputs": [], "prompt_number": 49 }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "Let's now test our priority queue. We'll add in several strings prioritized by their length, and verify that our priority queue will return the longest ones first:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "emptyQueue :: PriorityQueue String\n", "emptyQueue = PriorityQueue Empty\n", "\n", "strings :: [String]\n", "strings = [\"Goodbye\", \"one\", \"Hello\", \"a\"]\n", "\n", "-- Create a queue by putting in each of the strings.\n", "queue = foldr addToQueue emptyQueue strings\n", " where addToQueue str queue = push queue str (length str)\n", "\n", "let (longest, queue') = pop queue\n", "putStrLn longest -- Goodbye\n", "\n", "let (longest, queue'') = pop queue'\n", "putStrLn longest -- Hello\n", "\n", "let (longest, queue''') = pop queue''\n", "putStrLn longest -- one\n", "\n", "let (longest, _) = pop queue'''\n", "putStrLn longest -- a" ], "language": "python", "metadata": { "hidden": false }, "outputs": [ { "metadata": {}, "output_type": "display_data", "text": [ "Goodbye" ] }, { "metadata": {}, "output_type": "display_data", "text": [ "Hello" ] }, { "metadata": {}, "output_type": "display_data", "text": [ "one" ] }, { "metadata": {}, "output_type": "display_data", "text": [ "a" ] } ], "prompt_number": 50 }, { "cell_type": "markdown", "metadata": { "hidden": false }, "source": [ "# Conclusion\n", "\n", "Finger trees, as described by [Hinze and Patterson](http://www.soi.city.ac.uk/~ross/papers/FingerTree.html), are a pretty awesome data structure. They provide amortized constant time append and prepend (assuming a use case of repeated appends and prepends), amortized constant time left and right views, and logarithmic time concatenation. They can be parameterized by a monoidal annotation; then, given a monotonic boolean predicate on the monoidal annotations, a search can be performed in logarithmic time to determine which element (if any) tipped the scales and caused the incremental monoidal sum along the sequence to pass the predicate. This very general search algorithm allows very high code reuse \u2013 by changing the type stored by the finger tree and adding two typeclass instances, finger trees can be used as very different data structures. In this guide, we used finger trees to implement random-access functional sequences and priority queues with push and pop. In the original paper, they also describe several other data structures and operations, including ordered sequences (with access and insert) and interval trees. Due to the efficiency and asymptotic guarantees provided by finger trees, they are the basis for the sequences provided in the Haskell base library under the Data.Sequence module.\n", "\n", "This guide is written as an [IHaskell](http://www.github.com/gibiansky/IHaskell) notebook. If you would like to work with it interactively, you may [download it as a ntoebook](files/Finger-Trees.ipynb)." ] } ], "metadata": {} } ] }