Skip to content

Instantly share code, notes, and snippets.

@kunigami
Last active July 9, 2017 00:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kunigami/219150bb5566a3907a356532e20c04dd to your computer and use it in GitHub Desktop.
Save kunigami/219150bb5566a3907a356532e20c04dd to your computer and use it in GitHub Desktop.
Inserting binomial tree
(*
Links two trees of same rank r. The resulting tree has rank r + 1
*)
let link (tree1: tree) (tree2: tree) = match (tree1, tree2) with
(Node (node1, children1), Node (node2, children2)) ->
if (Element.compare node1 node2) <= 0
then Node (node1, tree2 :: children1)
else Node (node2, tree1 :: children2)
;;
(*
Insert a tree into a stream of digits. This assumes that
the rank of the tree being inserted has the rank corresponding to the
position of the current digits.
This is analogous to the carrying over operation of adding a 1 to a binary
number. For example, if we are to add 1 to 1011, then we'll have
101(11) -> match One, link -> 10(11)0
10(11)0 -> match One, link -> 1(1)00
1(1)00 -> match Zero -> 1100
*)
let rec insertTree (tree: tree) (digits: digit stream): digit stream =
match digits with
| lazy Nil -> Stream.empty |> Stream.insert (One tree)
| lazy (StreamCell (firstDigit, rest)) -> match firstDigit with
| Zero -> Stream.insert (One tree) rest
| One firstTree ->
lazy (StreamCell (Zero, (insertTree (link tree firstTree) rest)))
;;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment