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