krlawrence / graph

Practical Gremlin - An Apache TinkerPop Tutorial
Apache License 2.0
836 stars 253 forks source link

Add example of how index can be used to reverse a list #220

Closed krlawrence closed 1 year ago

krlawrence commented 3 years ago

Gremlin does not have a reverse step but a list can be reversed using the index step couples with order and tail

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]     
krlawrence commented 1 year ago

Closing as this is fixed and work has now started on the second edition. There will likely be one final release of the v283 first edition line before the V2 branch becomes the second edition. That release will include these fixes.