Content deleted Content added
Line 541:
- : string = "555-1212"
</source>
The code above uses OCaml's default hash function <code>Hashtbl.hash</code>, which is defined automatically for all types. If you wanted to use your own hash function, you can use the functor interface <code>Hashtbl.Make</code> to create a module, like with <code>Map</code> below.
Finally, functional maps (represented as immutable balanced binary trees):
<source lang="ocaml">
#
...
# let m = StringMap.add "Sally Smart" "555-9999" StringMap.empty
let m = StringMap.add "John Doe" "555-1212" m
let m = StringMap.add "J. Random Hacker" "553-1337" m;;
val m : string StringMap.t = <abstr>
# StringMap.find "John Doe" m;;
- : string = "555-1212"
</source>
Note that in order to use <code>Map</code>, you have to provide the functor <code>Map.Make</code> with a module which defines the key type and the comparison function. The third-party library ExtLib provides a polymorphic version of functional maps, called [http://ocaml-extlib.googlecode.com/svn/doc/apiref/PMap.html PMap], where you provide the comparison function when creating the map.
Lists of pairs and functional maps both provide a purely functional interface. In contrast, hash tables provide an imperative interface. For many operations, hash tables are significantly faster than lists of pairs and functional maps.
|