How to write the `apply` function in postgresql I'm trying to figure out how to use arrays as inputs to variadic functions and to have a function resembling apply in other languages.
So for instance, what's the best way of writing apply in the following statement?
DROP FUNCTION IF EXISTS test_greatest;

CREATE FUNCTION test_greatest(arr INT[]) RETURNS INT AS $$
BEGIN
    RETURN apply(greatest, arr)
END;
$$ LANGUAGE plpgsql;

SELECT test_greatest(ARRAY[1,6,3])
-- OUTPUTS 6

I found that unnest can works by converting an array into a relation:
DROP FUNCTION IF EXISTS test_max;

CREATE FUNCTION test_max(arr INT[]) RETURNS INT AS $$
BEGIN
    RETURN max(z) FROM unnest(arr) as z;
END;
$$ LANGUAGE plpgsql;

SELECT test_max(ARRAY[1,6,3])
-- OUTPUTS 6

but I'd really like to be able to write sql functions with apply.
I'd really like to be able to write sql functions with apply ...

Short answer: You can't.
Not with PostgreSQL.

... to have a function resembling apply in other languages.

Never come across &quot;apply&quot;, myself nor do I think it &quot;adds&quot; much to the code.
Given that you'll spend far more time reading [other people's] SQL than writing it, which of these is clearer / easier to understand?
return apply( greatest, arr );
return greatest( arr );

Now, I could see the attraction if you were writing your code in 'C' and so could use Function Pointers for that first argument, which can be immensely powerful, but in a SQL context?  I can't really see the benefit.