https://wiki.haskell.org/index.php?title=The_Monad.Reader/Issue4/On_Treaps_And_Randomization&feed=atom&action=historyThe Monad.Reader/Issue4/On Treaps And Randomization - Revision history2016-04-30T00:24:25ZRevision history for this page on the wikiMediaWiki 1.19.14+dfsg-1https://wiki.haskell.org/index.php?title=The_Monad.Reader/Issue4/On_Treaps_And_Randomization&diff=20879&oldid=prevGwern: fmt2008-05-10T01:08:44Z<p>fmt</p>
<table class='diff diff-contentalign-left'>
<tr valign='top'>
<td colspan='1' style="background-color: white; color:black;">← Older revision</td>
<td colspan='1' style="background-color: white; color:black;">Revision as of 01:08, 10 May 2008</td>
</tr></table>Gwernhttps://wiki.haskell.org/index.php?title=The_Monad.Reader/Issue4/On_Treaps_And_Randomization&diff=20838&oldid=prevWouterSwierstra at 14:23, 9 May 20082008-05-09T14:23:36Z<p></p>
<p><b>New page</b></p><div>'''This article needs reformatting! Please help tidy it up.'''--[[User:WouterSwierstra|WouterSwierstra]] 14:23, 9 May 2008 (UTC)<br />
<br />
= Treaps and Randomization in Haskell =<br />
''by Jesper Louis Andersen <jlouis@mongers.org> for The Monad.Reader IssueFour''<br />
[[BR]]<br />
''05/07 - 2005''<br />
<br />
'''Abstract.'''<br />
We give an example implementation of Treaps in Haskell. The emphasis is partly on treaps, partly on the System.Random module from the hierachial libraries. We show how to derive the code and explain it in an informal style. <br />
<br />
== Introduction ==<br />
<br />
I have, a number of times, warned people that I ought to do a TMR<br />
article. The world had its way, and I had to wait<br />
until the Summer to be able to finish an article. So this is<br />
it. Originally, I considered playing around with the<br />
ALL-PAIRS-SHORTEST-PATH algorithms, but for some reason I was<br />
not really satisfied with it. Also, with the upcoming Matrix library in the hierachial libraries, this might prove to be a better solution.<br />
<br />
Instead I will provide a treatise on the ''Treap'' data structure,<br />
devised by Aragon and Seidel. I have much to thank them for in the<br />
following. Usually citations are at the back of an article, but I<br />
really advise you to read ''Randomized Search Trees'' (Algorithmica,<br />
16(4/5):464-497, 1996). This document owes about 90% to the mentioned article.<br />
<br />
I also advise you to check out Oleg Kiselyovs work on treaps for<br />
Scheme. He does a number of optimizations on the data structure which<br />
I have skipped over here. Take a look at [http://okmij.org/ftp/Scheme/lib/treap.scm Olegs Scheme Treap implementation]<br />
<br />
== Search trees ==<br />
<br />
The classic problem of computer science is how to express and<br />
represent a finite map in a programming language. Formally a finite<br />
map is a function ''f: K --> V'', which is said to map a finite<br />
set ''K'', of keys, to a (thus also finite) set ''V'', of values. The<br />
basic functions are: ''lookup(f, k)'', which will return the value<br />
''f(k)'' in ''V'', associated with the value ''k'' in ''K''; ''insert(f, (k,v))''<br />
which extends or updates the finite map with a new key/value pair; and<br />
finally, ''delete(f, k)'', which removes the association of ''k'' from ''f''.<br />
<br />
One such representation is the binary search tree (In much litterature,<br />
the acronym BST is used). I assume most readers of TMR are familiar<br />
with binary search trees, and especially the pathological case degenerating the worst case search time bounds to ''O(n)''.<br />
<br />
There are a number of strategies for avoiding the degenerate case where the tree becomes a linked list in effect. One could be<br />
to add invariants to the tree, which ensures that it stays<br />
inside certain balance bounds. One example is the AVL<br />
tree, which maintains the following<br />
invariant: At each node, the child-subtrees differ in depth by at most<br />
1. This ensures the AVL-tree is always balanced and the pathological<br />
case where a tree is actually a list is ruled out. As a side note,<br />
an AVL tree will never be worse in structure than a fibonacci tree[[FootNote(Knuth, The Art of Computer Programming Volume 3 has a good treatment of this tree type)]].<br />
<br />
Another famous example is the Red-Black tree, which provides a less <br />
strict balance invariant than the AVL tree. The invariant is harder <br />
to describe in a single paragraph -- but involves colouring nodes either<br />
red or black and adding invariants such that the tree always stays <br />
reasonably balanced. See Introduction to algorithms by Cormen, Leiserson, Rivest and Stein if you want to read the hard, incomprehensible imperative<br />
version of this data structure, or Purely Functional Data Structures by Chris Okasaki if you want the functional approach to this (the functional code is a mere 12 lines without the '''delete''' operation).<br />
<br />
The '''Data.Map''' module in the hierachial libraries of Haskell<br />
use another type of tree known as the ''2-3 tree''. The ''2-3 tree'' is self-balancing but uses a different trick. A ''2-3 tree'' node contains<br />
either one or two ''(k, v)''-pairs and thus has either 2 or 3<br />
children. We call a node with 2 children a 2-node and a node with 3 children a 3-node. Insertions are always done into leaf nodes which can grow from 2-nodes to 3-nodes in a natural way. Growth of a 3-node is then done by splitting the node into two 2-nodes; the least ''(k, v)''-pair, the greatest pair and the middle pair is inserted into the parent node[[FootNote(There is a reference inside the documentation of the Data.Map)]].<br />
<br />
''Sadly, the above is not true. Data.Map has binary trees which are balanced according to the size of the left and right subtrees. If one subtree grows beyond a certain constant factor it is rebalanced'' -- JesperAndersen<br />
<br />
Yet another variant of the finite map is the splay tree. In the splay tree<br />
the rebalancing is done according to a simple heuristic which<br />
amortized over a certain number of operations yields ''O(lg n)''<br />
worst case running time. Splay trees are not that good for purely<br />
functional languages, since they change the tree for all<br />
operations, including '''lookup'''. Thus our type for a '''lookup''' <br />
function would be:<br />
<br />
{{{#!syntax haskell<br />
Splay_lookup :: key -> SplayTree key value -> (Maybe value, SplayTree)<br />
}}}<br />
<br />
As a consequence, the programmer has to ''thread'' his splay tree<br />
around where she wants to use it. This tends to clutter the code a<br />
great deal. Further, splay trees are not friendly to a cache or page<br />
hierachy, since the constant updating of nodes tends to dirty more <br />
pages/cache lines than necessary - but it hurts an imperative language <br />
more than a functional one which already has a fair deal of copying to do, due <br />
to persistence.<br />
<br />
'''Side Note''': a paging hierachy can be seen as a cache<br />
hierachy, if you take the swap space as the lowest level, page table mapped pages as the second level and TLB mapped pages as the third (and fastest) level.<br />
<br />
== Heaps ==<br />
<br />
A basic Queue (FIFO) is something I assume all know. A priority queue<br />
is a queue, where each element is assigned a priority from a totally<br />
ordered set P. Elements in the priority queue are extracted<br />
according to the order of the priorities. For the case where the order is<br />
increasing, the queue is often called a min-priq, since the minimum priority<br />
element is extracted first. Of course, a max-priq is also possible.<br />
<br />
Priority queues are often implemented as heaps. In a functional<br />
setting, a very simple heap to program is the pairing heap, which<br />
takes no more than 12 lines of Haskell. Unfortunately, this article is<br />
not about pairing heaps. Instead, we need the all familiar binary<br />
heap.<br />
<br />
A binary heap is a binary tree, where each node is a queue element and<br />
a priority. For the min-priq case, each node in the tree has a<br />
priority less than the priorities of its children. If a node is placed<br />
at the leaf of such a tree, it can be ''floated'' up by comparing it<br />
and its parent, eventually exchanging their places until the priority invariant has been fulfilled. Similarily, a node<br />
can be floated down by comparing the children priorities to each<br />
other, and exchanging the node for the child with the least priority.<br />
<br />
== Treaps ==<br />
<br />
So, why attempt another data structure for the finite map problem?<br />
One, it is fun. Two, this algorithm is so simple, it can be explained in a single, tiny(??), TMR article. Third, we need more TMR articles. Simplicity usually means a fast algorithm. Benchmarking treaps against<br />
'''Data.Map''' was my original idea and maybe a follow-up article<br />
will do carry out this benchmarking.<br />
<br />
While the introduction mentions finite maps, we will explore the simpler case where V is the singleton {True} set. The map ''f'' then represents a set of keys ''K'', since a key is either mapped to '''True''' or it is not, in which case we can return '''False'''. Thus, we do not even bother storing the singleton {True} set in the Treap structure. However, extending the treap to also posses arbitrary value data at each node is trivial and left as an exercise to the (interested, practically oriented) reader. <br />
<br />
Let ''K'' be a totally ordered space of keys. It is clear a binary<br />
search tree can be formed obeying this order. Formally, for each node,<br />
the left subtree contains keys less than the key at the node and<br />
the right subtree contains keys greater than the key at the node.<br />
<br />
Let ''P'' be a totally ordered set of priorities. It is clear we can<br />
form a binary min-heap containing the elements of ''P''. Formally, for<br />
each node, the subtrees contains keys ordering greater than the key at<br />
the node.<br />
<br />
Associate with each key ''k'' in ''K'' a priority ''p'' in ''P''. A<br />
'''Treap''' is then a binary tree obeying the binary search tree<br />
property with respect to the ''K''s as well as the min-priq property of<br />
the ''P''s. Now, if the priorities are chosen randomly, we will<br />
actually achieve a balanced tree (!). It might be wise to try to draw<br />
such a tree. In fact it is unique. To see this, construct the tree by<br />
inserting ''K''s in increasing order of priorities, by using the binary <br />
search tree '''insert''' algorithm.<br />
<br />
== Show me da' Code! ==<br />
<br />
Enough talk. Haskell! A module representing treaps is first defined:<br />
<br />
{{{#!syntax haskell<br />
module Treap (<br />
RTreap<br />
, empty<br />
, null<br />
, insert<br />
, delete<br />
, member<br />
, stdGenTreap<br />
, splitTreap<br />
, joinTreap<br />
) where<br />
<br />
import System.Random<br />
import Prelude hiding (null)<br />
}}}<br />
<br />
A treap is a binary search tree, where each node<br />
has a key and a priority:<br />
<br />
{{{#!syntax haskell<br />
data Treap k p = Leaf | Branch (Treap k p) k p (Treap k p)<br />
deriving (Show, Read)<br />
}}}<br />
<br />
The empty tree and the null predicate are simple. They are copied<br />
verbatim from the binary search tree:<br />
<br />
{{{#!syntax haskell <br />
treap_Empty :: Treap k p<br />
treap_Empty = Leaf<br />
<br />
treap_Null :: Treap k p -> Bool<br />
treap_Null Leaf = True<br />
treap_Null _ = False<br />
}}}<br />
<br />
Insertion into a treap works by inserting the node, as if inserting<br />
into a binary search tree. Then we use the famous left- and<br />
right-rotations to float the node up, until it fullfills the<br />
heap-property on its priority. If you are not familiar with left and<br />
right rotations, they are just restructurings of a binary search tree,<br />
maintaining the ordering property. What is important is they alter the<br />
heights of the subtrees and so can help balance the tree more. They are easily <br />
defineable in Haskell by pattern matching. Drawing them on paper is a good <br />
exercise:<br />
<br />
{{{#!syntax haskell<br />
rotateLeft :: Treap k p -> Treap k p<br />
rotateLeft (Branch a k p (Branch b1 k' p' b2)) =<br />
Branch (Branch a k p b1) k' p' b2<br />
rotateLeft _ = error "Wrong rotation (rotateLeft)"<br />
<br />
rotateRight :: Treap k p -> Treap k p<br />
rotateRight (Branch (Branch a1 k' p' a2) k p b) =<br />
Branch a1 k' p' (Branch a2 k p b)<br />
rotateRight _ = error "Wrong rotation (rotateRight)"<br />
<br />
treap_Insert :: (Ord k, Ord p) => k -> p -> Treap k p -> Treap k p<br />
treap_Insert k p Leaf = Branch Leaf k p Leaf<br />
treap_Insert k p (Branch left k' p' right) =<br />
case compare k k' of<br />
EQ -> Branch left k' p' right -- Node is already there, ignore<br />
LT -> case Branch (treap_Insert k p left) k' p' right of<br />
(t @ (Branch (Branch l' k p r') k' p' right)) -><br />
if p' > p<br />
then rotateRight t<br />
else t<br />
t -> t<br />
GT -> case Branch left k' p' (treap_Insert k p right) of<br />
(t @ (Branch left k' p' (Branch l' k p r'))) -><br />
if p' > p<br />
then rotateLeft t<br />
else t<br />
t -> t<br />
}}}<br />
<br />
When coding structures based upon binary trees it can be convenient to ''forget'' the deletion case. It is often the hardest<br />
case to grasp and it can be quite hard to maintain invariants<br />
associated with the tree such as the AVL-tree or Red/Black-tree. Not<br />
so for Treaps, however. We just locate the node by a binary tree search and<br />
then float it down by rotations until the node is a leaf using the<br />
heap-properties and operations. Then we cut<br />
off the leaf (Notice the nice metaphors, please).<br />
<br />
{{{#!syntax haskell<br />
treap_Delete :: (Ord k, Ord p) => k -> Treap k p -> Treap k p<br />
treap_Delete k treap = recDelete k treap<br />
where recDelete k Leaf = error "Key does not exist in tree (delete)"<br />
recDelete k (t @ (Branch left k' p right)) =<br />
case compare k k' of<br />
LT -> Branch (recDelete k left) k' p right<br />
GT -> Branch left k' p (recDelete k right)<br />
EQ -> rootDelete t<br />
priorityCompare Leaf (Branch _ _ _ _) = False<br />
priorityCompare (Branch _ _ _ _) Leaf = True<br />
priorityCompare (Branch _ _ x _) (Branch _ _ y _) = x < y<br />
rootDelete Leaf = Leaf<br />
rootDelete (Branch Leaf _ _ Leaf) = Leaf<br />
rootDelete (t @ (Branch left k p right)) =<br />
if priorityCompare left right<br />
then let Branch left k p right = rotateRight t<br />
in Branch left k p (rootDelete right)<br />
else let Branch left k p right = rotateLeft t<br />
in Branch (rootDelete left) k p right<br />
}}}<br />
<br />
We must not forget the '''member''' function. This is simple, as it<br />
is nothing but the original binary search tree function:<br />
<br />
{{{#!syntax haskell<br />
treap_Member :: (Ord k, Ord p) => k -> Treap k p -> Bool<br />
treap_Member e Leaf = False<br />
treap_Member e (Branch left k _ right) =<br />
case compare e k of<br />
LT -> treap_Member e left<br />
GT -> treap_Member e right<br />
EQ -> True<br />
}}}<br />
<br />
== Providing random priorities ==<br />
<br />
The premise of the Treap algorithm is the provision of a good random<br />
number generator. If the priorities are randomly assigned, the tree<br />
will be balanced well (with a high probability). So, our next quest is<br />
to assign priorities randomly to each node. The random<br />
assignment also makes it impossible for an evil adversary to unbalance<br />
the structure.<br />
<br />
There are numerous possibilities, but the one shining most is<br />
the '''System.Random''' library. The library provides<br />
us with 2 type classes '''Random``Gen''' and '''Random'''. The<br />
'''Random``Gen''' class are those types ''g'', which can be used as<br />
random number generators. The '''Random''' class on the other hand<br />
are those types ''a'', from which random values can be drawn. That<br />
is, given a type of class '''Random``Gen''', any value with a type of class '''Random''' can be drawn from it.<br />
<br />
The '''System.Random''' library also provides a standard random<br />
number generator. For our purpose it has the disadvantage of being<br />
wrapped inside the '''IO''' monad and having to rely on a monad for our treap operations is bad since we then have to thread the monad around with us.<br />
<br />
Thus the plan is the following: Initialize a treap as a random number<br />
generator and the structure above. Then maintain the random number<br />
generator while running operations in the treap. We call this<br />
structure an '''RTreap''':<br />
<br />
{{{#!syntax haskell<br />
newtype RTReap g k p = RT (g, Treap k p)<br />
deriving (Show, Read)<br />
}}}<br />
<br />
The empty treap is then an initialization of the random number<br />
generator, as said. The null predicate is just a simple re-usage of<br />
the function above:<br />
<br />
{{{#!syntax haskell<br />
empty :: RandomGen g => g -> RTreap g k p<br />
empty g = RT (g, treap_Empty)<br />
<br />
null :: RandomGen g => RTreap g k p -> Bool<br />
null (RT (g, t)) = treap_Null t<br />
}}}<br />
<br />
Insertion into the treap is done by requesting a new random number<br />
from our supply and using this for the node in question. Delete and<br />
member are just the same from above with some added structure.<br />
<br />
Note we draw random values in a bounded area, such that we have a<br />
value less than every random priority in the treap and a value greater<br />
than every random priority in the heap. There are certain tricks which<br />
can be pulled with these values.<br />
<br />
{{{#!syntax haskell<br />
insert :: (RandomGen g, Ord k, Ord p, Num p, Random p)<br />
=> k -> RTreap g k p -> RTreap g k p<br />
insert k (RT (g, tr)) =<br />
let (p, g') = randomR (-2000000000, 2000000000) g<br />
in RT (g', treap_Insert k p tr)<br />
<br />
delete :: (RandomGen g, Ord k, Ord p) => k -> RTreap g k p<br />
-> RTreap g k p<br />
delete k (RT (g, tr)) = RT (g, treap_Delete k tr)<br />
<br />
member :: (RandomGen g, Ord k, Ord p) => k -> RTreap g k p<br />
-> Bool<br />
member k (RT (g, tr)) = treap_Member k tr<br />
}}}<br />
<br />
The initialization of the '''RTreap''' will then be something like:<br />
<br />
{{{#!syntax haskell<br />
stdGenTreap :: Int -> RTreap StdGen k p<br />
stdGenTreap = (empty . mkStdGen)<br />
}}}<br />
<br />
The ''Int'' type one has to provide is an initialization seed. We can get one such inside an '''IO''' monad when starting our program and then use it to seed the Treaps we need afterwards. The functions needed are defined inside the '''System.Random''' module.<br />
<br />
== Cool additions ==<br />
<br />
If we wish to split a treap at a certain node k in K, we can do so,<br />
by inserting k with the minimum priority. Assuming p are in the<br />
'''Bounded''' class:<br />
<br />
{{{#!syntax haskell<br />
splitTreap :: (RandomGen g, Bounded p, Ord k, Ord p)<br />
=> k -> RTreap g k p -> (RTreap g k p, RTreap g k p)<br />
splitTreap k (RT (g, tr)) =<br />
let (g', g'') = split g<br />
Branch left _ _ right = treap_Insert k minBound tr<br />
in (RT (g', left), RT (g'', right))<br />
}}}<br />
<br />
Similarily to join two ''disjoint'' treaps with key spaces K1 and K2, where the keys in K1 are smaller than the keys in K2 (formally: max K1 < min K2), we can<br />
choose a key k not in the union (K1, K2) and form the tree where k is the<br />
root and the treaps are left and right children. We then proceed by<br />
deleting the node k:<br />
<br />
{{{#!syntax haskell<br />
joinTreap :: (Bounded p, Ord p, Ord k)<br />
=> k -> RTreap g k p -> RTreap g k p -> RTreap g k p<br />
joinTreap k (RT (g, tr1)) (RT (_, tr2)) =<br />
RT (g, (treap_Delete k (Branch tr1 k maxBound tr2)))<br />
}}}<br />
<br />
== Optimizations ==<br />
<br />
I will simply direct people to the article by Oleg pointed at in the introduction. There are certain optimizations possible, which he thoroughly discusses. Implementing these is an exercise.<br />
----<br />
CategoryArticle</div>WouterSwierstra