Charles Greathouse on Thu, 17 Oct 2013 19:12:04 +0200


[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Re: gp/pari version of the "Map" datatype and "reduce" function


I think "fold" is good and avoids clashes.

Charles Greathouse
Analyst/Programmer
Case Western Reserve University


On Thu, Oct 17, 2013 at 7:42 AM, Bill Allombert <Bill.Allombert@math.u-bordeaux1.fr> wrote:
On Wed, Oct 16, 2013 at 11:32:50PM +0100, Richard Heylen wrote:
> 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.

This is difficult to implement efficiently in the GP design which lacks a
garbage collector.  Karim managed to implement usable lists, but they do not
work with GP2C.

> 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.

it is a ggood suggestion, but you can implement reduce in GP easily:

reduce(f,v)=my(s=v[1]);for(i=2,#v,s=f(s,v[i]));s

I could add it to PARI but we need to settle on a name.

Cheers,
Bill.