Re: array/function question

From: Alvaro Herrera <alvherre(at)commandprompt(dot)com>
To: Joshua Berry <yoberi(at)gmail(dot)com>
Cc: postgresql Forums <pgsql-general(at)postgresql(dot)org>
Subject: Re: array/function question
Date: 2009-05-18 23:49:26
Message-ID: 20090518234926.GQ10339@alvh.no-ip.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Joshua Berry escribió:

> Inputs:
> A: an array of integers. for example: { 1, 2, 3, 4, 7 }
> B: an array of integers. for example: { 1, 4, 8, 9 }
>
> Returns
> C: an array of bools the same dimensions as Array A. In this example: {
> true, false, false, false, true, false }
>
> Effectively, this function would use Array A as a set of boolean tests
> to exercise on Array B. The result array will have the save number of
> elements as array A.

I think this is much easier to write in PL/Perl than PL/pgSQL. Trivial
in fact. Your example is flawed though (three falses instead of two) ...
I think it looks like this:

create or replace function is_element_present(int[], int[]) returns bool[] language plperl as $$
$a = shift;
$b = shift;
if ($a =~ /{(.*)}/) {
@a = split /,/, $1
}
if ($b =~ /{(.*)}/) {
@b = split /,/, $1
}
for my $k (@b) {
$h{$k} = 1;
}
@c = map { if (defined $h{$_}) { 1 } else { 0 } } @a;
return \(at)c;
$$;

Hmm, well, the fact that PL/Perl passes arrays as string kinda sucks --
fixing that takes half the code of the function!

alvherre=# select is_element_present('{1,2,3,4,7}', '{1,4,8,9}');
is_element_present
--------------------
{t,f,f,t,f}
(1 fila)

--
Alvaro Herrera http://www.CommandPrompt.com/
The PostgreSQL Company - Command Prompt, Inc.

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Alvaro Herrera 2009-05-18 23:57:07 Re: Commit visibility guarantees
Previous Message Marsh Ray 2009-05-18 23:44:36 Re: Commit visibility guarantees