Each entry in a hash table consists of a key and a value. We provide three ways to map functions over a hash table, depending on whether the function is to receive a value and return a new value, to receive a key and return a new key, or to receive a key-value pair and return a new key-value pair. The corresponding functions, applyValues, applyKeys, and applyPairs are illustrated in the next example.
i1 : x = new HashTable from {a=>1, b=>2} |
i2 : applyValues(x, value -> 1000*value) |
i3 : applyKeys(x, key -> {key}) |
i4 : applyPairs(x, (key,value) -> (value,key)) |
The functions, scanValues, scanKeys, and scanPairs are similar, but the values returned are discarded instead of being assembled into a new hash table.
i5 : x = new HashTable from {a=>1, b=>2} |
i6 : scanValues(x, print) |
i7 : scanKeys(x, print) |
i8 : scanPairs(x, print) |
The function merge can be used to merge two hash tables. The result is a hash table whose keys are those occuring in one of the two incoming hash tables. We must provide a function of two arguments that is used to combine the values when a key occurs in both hash tables.
i9 : y = new HashTable from {b=>200, c=>300} |
i10 : merge(x, y, plus) |
The function combine can be used to combine two hash tables x and y into a new hash table. Three functions must be provided. The first one produces new keys from a key of x and a key of y. The second one produces a new values from a value of x and a value of y. The third one is used to combine values when two new keys turn out to be the same.
i11 : combine(x,y,identity,times,plus) |