Gremlin queries often work with or produce lists. Sometimes it is desirable to be able to reverse a list. Currently Gremlin does not have a reverse
step so you cannot do something like:
g.inject(['A','B','C','D']).reverse()
Nor is there a reverse
option for order
so you cannot do something like
g.inject(['A','B','C','D']).order(local).by(reverse)
Is there a way to reverse a list in Gremlin today without having to fall back on using closures?
It is possible to do this today using just existing Gremlin steps. The example below takes advantage of the index
step to give each element of a list an index number. For example:
gremlin> g.inject(['A','B','C','D']).index()
==>[[A,0],[B,1],[C,2],[D,3]]
Given that building block, we can use those index values and order the list.
gremlin> g.inject(['A','B','C','D']).index().
......1> unfold().
......2> order().
......3> by(tail(local,1),desc)
==>[D,3]
==>[C,2]
==>[B,1]
==>[A,0]
The last step is to return the reordered list with the index values removed.
gremlin> g.inject(['A','B','C','D']).index().
......1> unfold().
......2> order().
......3> by(tail(local,1),desc).
......4> limit(local,1).
......5> fold()
==>[D,C,B,A]