Thread: Defining functions for arrays of any number type

Defining functions for arrays of any number type

From
Paul Jungwirth
Date:
Hello,

I'm working on a package of functions that compute statistics on
arrays of numbers. For example this one computes a histogram from a
bunch of values plus some bucket characteristics:

CREATE OR REPLACE FUNCTION
array_to_hist(double precision[], double precision, double precision, int)
RETURNS int[]
AS 'aggs_for_arrays', 'array_to_hist'
LANGUAGE c;

Now suppose I wanted this function to accept not just arrays of double
precision values, but arrays of any numeric type. I don't see any
pseudotype like that in this list:

http://www.postgresql.org/docs/9.3/static/datatype-pseudo.html

So how would you declare this function? Should I use anyarray for the
first parameter and anyelement for the next two (start of first bucket
and bucket width), and then just have the implementation complain if
the type isn't numeric? Or is there a better way than that?

Is it legal to define a bunch of functions all called `array_to_hist`
for the different numeric types, and have them all implemented by the
same C function?

Thanks,
Paul

--
_________________________________
Pulchritudo splendor veritatis.


Re: Defining functions for arrays of any number type

From
Tom Lane
Date:
Paul Jungwirth <pj@illuminatedcomputing.com> writes:
> Is it legal to define a bunch of functions all called `array_to_hist`
> for the different numeric types, and have them all implemented by the
> same C function?

Sure.

(There is a regression test that objects if we try to do that with
built-in functions, but it's meant to catch accidental errors rather
than intentional overloading.  As long as the C code is prepared to
handle all the cases, you can do what you like.)

            regards, tom lane