Module "sequence"

This module is inspired by SQL query options such as TOP. Providing such a module was recently pioneered by SWI-Prolog. Currently predicates limit/2, offset/2, call_nth/2, distinct/1 and order_by/2 are provided. The predicates solely work tuple oriented and it is possible to cascade these predicates:

?- limit(5, offset(3, between(1, 10, X))).
X = 4 ;
X = 5 ;
X = 6 ;
X = 7 ;
X = 8

The current implementation of limit/2 and offset/2 is based on call_nth/2. The predicate call_nth/2 is in turn implemented with pivots, an alternative to nb_setarg/3 which does not destruct a Prolog term, but instead a Java object. The implementation of distinct/1 and order_by/2 uses a custom Java object as well.

?- order_by([asc(X)], member(X, [red, green, blue])).
X = blue ;
X = green ;
X = red
?- order_by([desc(X)], member(X, [red, green, blue])).
X = red ;
X = green ;
X = blue

The order_by/2 order functions are currently limited to ASC and DESC, both using the ISO core standard compare/3 under the hood. The order_by/2 predicate can be combined with a goal wrapped in distinct/1 and it will then directly de-duplicate the unsorted part of the solutions in an efficient way.

The following sequence predicates are provided:

limit(C, G):
The predicate succeeds whenever the goal G succeeds but limits the number of solutions to C.
offset(C, G):
The predicate succeeds whenever the goal G succeeds except for the first C solutions which are suppressed.
call_nth(G, C):
The predicate succeeds whenever G succeeds and unifies C with the numbering of the successes.
The predicates succeeds eagerly with only the first solutions of G.
order_by(W, G):
The predicates succeeds lazily and sorted with the solutions of G. Ordering is done according to the list of order function W. The following order functions are supported.

asc(T): Order the term T in ascending lexical order.
desc(T): Order the term T in descending lexical order.

The lexical order is the same as in compare/3.