Commit 6d75d13d authored by Kim Nguyễn's avatar Kim Nguyễn

Add patricia.cd file from Issue #21

parent 80620fde
(* Patricia trees
Chris Okasaki and Andrew Gill's paper Fast Mergeable Integer Maps
http://ittc.ku.edu/~andygill/papers/IntMap98.pdf
*)
type Leaf = <leaf key=Caml_int> 'a
type Branch = <brch pre=Caml_int bit=Caml_int>[ (Leaf|Branch) (Leaf|Branch) ]
type Dict = [] | Branch | Leaf
let lowest_bit (x: Caml_int): Caml_int = Pervasives.land x ((0 - x):?Caml_int)
let branching_bit (p0: Caml_int)(p1: Caml_int): Caml_int = lowest_bit (Pervasives.lxor p0 p1)
let mask (p: Caml_int) (m: Caml_int): Caml_int =
Pervasives.land p (Pervasives.pred m)
let matchPrefix (k: Caml_int)(p: Caml_int)(m: Caml_int): Bool =
mask p m = k
let zero_bit (k: Caml_int)(m: Caml_int): Bool = Pervasives.land k m = 0
let lookup (k: Caml_int)(d: Dict) : ['a?] =
match d with
| [] -> []
| <brch pre=p bit=m>[ t0 t1 ] ->
if not (matchPrefix k p m) then []
else if zero_bit k m then lookup k t0
else lookup k t1
| <leaf key=j> x -> if j=k then [ x ] else []
let join (p0: Caml_int, t0: Dict\[],p1: Caml_int,t1: Dict\[]): Leaf | Branch =
let m = branching_bit p0 p1 in
if zero_bit p0 m then
<brch pre=(mask p0 m) bit=m>[t0 t1]
else
<brch pre=(mask p0 m) bit=m>[t1 t0]
let insert (c: 'a -> 'a -> 'a) (k: Caml_int) (x: 'a) (t: Dict): Leaf|Branch =
let ins (Leaf|Branch -> Leaf|Branch ; [] -> Leaf )
| [] -> <leaf key=k> x
| (<leaf key=j>y)&t ->
if j=k then <leaf key=k>(c x y)
else join (k,<leaf key=k>x,j,t)
| (<brch pre=p bit=m>[ t0 t1 ])&t ->
if matchPrefix k p m then
if zero_bit k m then <brch pre=p bit=m>[ (ins t0) t1 ]
else <brch pre=p bit=m>[ t0 (ins t1) ]
else join (k,<leaf key=k>x,p,t)
in ins t
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment