Commit f374d866 authored by Taddeus Kroes's avatar Taddeus Kroes

funclang series4: Fixed insert function in ass9.

parent d4f3ab1f
......@@ -19,15 +19,32 @@ let rec insert trie key value =
else if starts_with key k then
(* Inserted key should be in this node because it starts with
* the node's key *)
let matches_key = function
| Empty -> false
| Node (k, _, c) -> starts_with key k
let rec walk_nodes = function
| [] -> Empty
| node::tail ->
match node with
| Empty -> Empty
| Node (k, _, _) ->
if starts_with key k then
Node (k, v, (insert node key value)::children)
else
walk_nodes tail
in
(* 'move' are the children that are moved to be the children of the
* inserted node, 'siblings' are the children that remain in the
* current matched node *)
let move, siblings = partition matches_key children in
Node (k, v, siblings @ [Node (key, value, move)])
(* First, check if the new pair should be inserted in one of the
* children. If not, prepend it to the children list while moving
* all children that are should be inside the new node *)
match walk_nodes children with
| Empty ->
let matches_key = function
| Empty -> false
| Node (k, _, _) -> starts_with k key
in
(* 'move' are the children that are moved to be the children of
* the inserted node, 'siblings' are the children that remain
* in the current matched node *)
let move, siblings = partition matches_key children in
Node (k, v, (Node (key, value, move))::siblings)
| node -> node
else
raise (Failure "Inserted key does not start with node key")
;;
......@@ -68,6 +85,6 @@ let rec matches trie key =
@ match_nodes children
;;
let a = Node ([1;2;3], "a", []);;
(*let a = Node ([1;2;3], "a", []);;
let b = Node ([1;3], "b", [a]);;
let c = Node ([3;4], "c", [b]);;
let c = Node ([3;4], "c", [b]);;*)
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