ocaml: phase 5.1 bag.ml baseline + String.equal/compare/cat/empty (+3 tests, 579 total)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 23s
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 23s
bag.ml: split a sentence on spaces, count each word in a Hashtbl, return the maximum count via Hashtbl.fold. count_words 'the quick brown fox jumps over the lazy dog the fox' -> Hashtbl with 'the' = 3 as the max -> 3 Exercises String.split_on_char + Hashtbl.find_opt/replace + Hashtbl.fold (k v acc -> ...). Together with frequency.ml from iter 84 we now have two Hashtbl-counting baselines exercising slightly different idioms. 29 baseline programs total. String additions: equal a b = a = b compare a b = -1 / 0 / 1 via host < / > cat a b = a ^ b empty = '' (constant)
This commit is contained in:
18
lib/ocaml/baseline/bag.ml
Normal file
18
lib/ocaml/baseline/bag.ml
Normal file
@@ -0,0 +1,18 @@
|
||||
let count_words text =
|
||||
let words = String.split_on_char ' ' text in
|
||||
let counts = Hashtbl.create 8 in
|
||||
List.iter (fun w ->
|
||||
let n = match Hashtbl.find_opt counts w with
|
||||
| Some n -> n + 1
|
||||
| None -> 1
|
||||
in
|
||||
Hashtbl.replace counts w n
|
||||
) words;
|
||||
counts
|
||||
|
||||
let max_count counts =
|
||||
Hashtbl.fold (fun _ v acc -> if v > acc then v else acc) counts 0
|
||||
|
||||
;;
|
||||
|
||||
max_count (count_words "the quick brown fox jumps over the lazy dog the fox")
|
||||
@@ -1,5 +1,6 @@
|
||||
{
|
||||
"anagrams.ml": 3,
|
||||
"bag.ml": 3,
|
||||
"bfs.ml": 6,
|
||||
"btree.ml": 39,
|
||||
"brainfuck.ml": 75,
|
||||
|
||||
Reference in New Issue
Block a user