Commit d4f3ab1f authored by Taddeus Kroes's avatar Taddeus Kroes

funclang series4: Implemented insert function for ass9.

parent 3143e5aa
...@@ -9,24 +9,30 @@ let rec starts_with l s = ...@@ -9,24 +9,30 @@ let rec starts_with l s =
| h::t -> h = (hd l) && starts_with (tl l) t | h::t -> h = (hd l) && starts_with (tl l) t
;; ;;
(* Insert a new (key, value) pair into a trie *)
let rec insert trie key value = let rec insert trie key value =
match trie with match trie with
| Empty -> Node (key, value, []) (* Root *) | Empty -> Node (key, value, []) (* Root *)
| Node (k, v, children) -> | Node (k, v, children) ->
if starts_with key k then if k = key then
(* Check all children for a longer prefix *) raise (Failure "Inserted key already exists in trie")
if (length k) = (length key) - 1 then else if starts_with key k then
(* Direct child *) (* Inserted key should be in this node because it starts with
Node (k, v, children @ [Node (key, value, [])]) * the node's key *)
else let matches_key = function
(* Add another nde between the matched node and the child, | Empty -> false
* with the length of the matched node plus one *) | Node (k, _, c) -> starts_with key k
Empty 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)])
else else
raise (Failure "Inserted key does not start with node key") raise (Failure "Inserted key does not start with node key")
;; ;;
(**) (* Look up a value associated with a key *)
let rec lookup trie key = let rec lookup trie key =
match trie with match trie with
| Empty -> None (* Trie is empty, so no result *) | Empty -> None (* Trie is empty, so no result *)
...@@ -49,6 +55,7 @@ let rec lookup trie key = ...@@ -49,6 +55,7 @@ let rec lookup trie key =
None None
;; ;;
(* Find all (key, value) pairs whose key start with a given prefix *)
let rec matches trie key = let rec matches trie key =
match trie with match trie with
| Empty -> [] | Empty -> []
......
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