Skip to content

Instantly share code, notes, and snippets.

@ThePhD
Last active September 29, 2016 14:20
Show Gist options
  • Save ThePhD/c128a3449bea99bff781455a46cf87c8 to your computer and use it in GitHub Desktop.
Save ThePhD/c128a3449bea99bff781455a46cf87c8 to your computer and use it in GitHub Desktop.
Help me I'm drowning in Functional
module StringMap = Map.Make(String);;
let update_count key map = try StringMap.add key ((StringMap.find key map) + 1) map with | Not_found -> StringMap.add key 1 map;;
(* This is like List.fold_left but I can't seem to get the types to match up with
List.fold_left... *)
let rec accumulate map = function (* Same as match x with ... *)
(* nothing to update, just return the map *)
(* update count, then handle rest *)
| [] -> map | h :: rest -> accumulate (update_count h map) rest;;
(* Booo *)
let count_words words = List.fold_left update_count StringMap.empty words
(* accumulate StringMap.empty words*);;
let counts = StringMap.bindings (count_words ["bark";"bark";"woof";"bark";"woof";"pant"]);;
List.iter ( fun ( x, y ) -> print_string x; print_string " "; print_int y; print_string "\n" ) counts;;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment