Writing functions in Postgres that returns strings with dots in reverse like java namespaces Looking for a Postgres 9.6 function that reverse sorts a string the same way that java namespaced packages do.  Preferable if this is just PGSQL, I know that this is simple in the V8 engine or Python.

I.e. if I have the string foo.bar.baz.example.com, I want the string com.example.baz.bar.foo.  My very naive attempts like running a 
REVERSE on the string didn't work.  

I'm thinking I would need to explode on the periods, (can you explode in Postgres?), start a cursor, loop over the set, insert the last item from the set, shift that item off the set, and continue until the set is empty.

But I don't know how to do any of that.
You can do this with a combination of array functions:

select string_agg(x, '.' order by idx desc)
from unnest(string_to_array('foo.bar.baz.example.com','.')) with ordinality as t(x, idx);


you can put this into a function if you want:

create function reverse_elements(p_words text)
  returns text
as
$$
  select string_agg(x, '.' order by idx desc)
  from unnest(string_to_array(p_words,'.')) with ordinality as t(x, idx);
$$
language sql;