ocaml: phase 5.1 trie.ml baseline (prefix tree, 6/9 word lookups match)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 22s
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 22s
Mutable-record trie with linked-list children:
type trie = {
mutable terminal : bool;
mutable children : (char * trie) list
}
Insert {cat, car, card, cart, dog, doge}; lookup 9 words. Hits are
exactly the inserted set: cat, car, card, cart, dog, doge = 6.
Misses: ca (prefix not terminal), dogs (extends 'dog' but no 'dogs'
node), x (no path).
Tests:
- recursive type definition with self-referential field
- mutable record fields with .field <- v
- Option pattern matching (Some / None)
- tuple-cons pattern (k, v) :: rest
146 baseline programs total.
This commit is contained in:
@@ -140,6 +140,7 @@
|
||||
"sum_squares.ml": 385,
|
||||
"tree_depth.ml": 4,
|
||||
"triangle.ml": 11,
|
||||
"trie.ml": 6,
|
||||
"triangle_div.ml": 120,
|
||||
"twosum.ml": 5,
|
||||
"union_find.ml": 4,
|
||||
|
||||
36
lib/ocaml/baseline/trie.ml
Normal file
36
lib/ocaml/baseline/trie.ml
Normal file
@@ -0,0 +1,36 @@
|
||||
type trie = { mutable terminal : bool; mutable children : (char * trie) list }
|
||||
|
||||
let make_trie () = { terminal = false; children = [] }
|
||||
|
||||
let rec lookup_child cs c =
|
||||
match cs with
|
||||
| [] -> None
|
||||
| (k, v) :: rest -> if k = c then Some v else lookup_child rest c
|
||||
|
||||
let rec insert t s i =
|
||||
if i = String.length s then t.terminal <- true
|
||||
else
|
||||
let c = s.[i] in
|
||||
match lookup_child t.children c with
|
||||
| Some child -> insert child s (i + 1)
|
||||
| None ->
|
||||
let nc = make_trie () in
|
||||
t.children <- (c, nc) :: t.children;
|
||||
insert nc s (i + 1)
|
||||
|
||||
let rec contains t s i =
|
||||
if i = String.length s then t.terminal
|
||||
else
|
||||
let c = s.[i] in
|
||||
match lookup_child t.children c with
|
||||
| Some child -> contains child s (i + 1)
|
||||
| None -> false
|
||||
|
||||
;;
|
||||
|
||||
let t = make_trie () in
|
||||
List.iter (fun w -> insert t w 0) ["cat"; "car"; "card"; "cart"; "dog"; "doge"];
|
||||
let count = ref 0 in
|
||||
List.iter (fun w -> if contains t w 0 then count := !count + 1)
|
||||
["cat"; "car"; "ca"; "card"; "cart"; "dog"; "doge"; "dogs"; "x"];
|
||||
!count
|
||||
Reference in New Issue
Block a user