Macaulay2 » Documentation
Packages » Macaulay2Doc > The Macaulay2 language > mapping over hash tables
next | previous | forward | backward | up | index | toc

mapping over hash tables -- apply a function to each element of a hash table

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}

o1 = HashTable{a => 1}
               b => 2

o1 : HashTable
i2 : applyValues(x, value -> 1000*value)

o2 = HashTable{a => 1000}
               b => 2000

o2 : HashTable
i3 : applyKeys(x, key -> {key})

o3 = HashTable{{a} => 1}
               {b} => 2

o3 : HashTable
i4 : applyPairs(x, (key,value) -> (value,key))

o4 = HashTable{1 => a}
               2 => b

o4 : HashTable
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}

o5 = HashTable{a => 1}
               b => 2

o5 : HashTable
i6 : scanValues(x, print)
i7 : scanKeys(x, print)
i8 : scanPairs(x, print)
(a, 1)
(b, 2)
The function merge can be used to merge two hash tables. The result is a hash table whose keys are those occurring 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}

o9 = HashTable{b => 200}
               c => 300

o9 : HashTable
i10 : merge(x, y, plus)

o10 = HashTable{a => 1  }
                b => 202
                c => 300

o10 : HashTable
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)

o11 = HashTable{(a, b) => 200}
                (a, c) => 300
                (b, b) => 400
                (b, c) => 600

o11 : HashTable