Search code examples
sortingprologswi-prolog

Sort list of list in prolog?


In SWI-Prolog there is the predicate sort/2 to sort lists. Is there a good way to sort a list of list with fixed length by some index. I mean in example, if I have the following list of elements

  • [[1,2], [3,1], [2, 5]]

Is there a function in SWI-Prolog to sort it by first or second index. By first index the result would be:

  • [[1,2], [2,5], [3, 1]]

By second index:

  • [[3,1], [1,2], [2, 5]]

Solution

  • Can use https://www.swi-prolog.org/pldoc/doc_for?object=predsort/3 if removing duplicates is OK:

    test(Nth1, S) :-
        L = [[1,2], [3,1], [2, 5], [1,2]],
        predsort(nth1_compare(Nth1), L, S).
        
    nth1_compare(Nth1, Comp, L1, L2) :-
        nth1(Nth1, L1, V1),
        nth1(Nth1, L2, V2),
        compare(Comp, V1, V2).
    

    Results:

    ?- test(1, S).
    S = [[1,2],[2,5],[3,1]].
    
    ?- test(2, S).
    S = [[3,1],[1,2],[2,5]].