Richard Heylen on Thu, 17 Oct 2013 00:33:01 +0200 |
[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]
gp/pari version of the "Map" datatype and "reduce" function |
When writing gp/pari programs I often have a function that produces lots of different discrete values and I want to record some data about these values. For example, I might want to accumulate sets of input values that result in the different output values. The key feature is that I don't really know what the output values are before I start running the function and they can't conveniently be converted into integers to be used as an index into an array. In other languages this is often addressed by providing a data type which can take an arbitrary value as a key and lets you set or return an arbitrary value associated with that key. As a bonus, it might be useful to be able to interate over the data in the order in which the keys were first used. I can achieve something similar at the moment using a combination of a Set to hold the keys and a Vector for the values, using setsearch to find the index for the vector but it's not nice. Also, pari/gp has functions "apply" and "select" which implement common functional programming ideas. A key one which seems to be missing is "reduce" (or "fold") which takes a vector, a function and an initial value and applies the function repeatedly to the value and the next element of the vector, using the return value as the value for the next iteration. For example reduce((a,b)->a+b,v,0) would return the sum of the elements of v. Any help would be appreciated! Richard