-
-
Save ThePhD/c128a3449bea99bff781455a46cf87c8 to your computer and use it in GitHub Desktop.
Help me I'm drowning in Functional
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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