Search code examples
swi-prolog

Why does sort/4 behave this way?


I needed to sort a list of three element sublists by their third element. I used sort/4 and it raised a weird error. So I read the documentation, had no clue what I did wrong and then tried it on a simple example. The error persisted.

Here are the queries I executed in the screenshot:

X = [ [1,2,3], [4,1,5], [3,5,2] ], sort( 2, @<, X, Y ).
X = [ [1,2,3], [4,1,5], [3,5,2] ], sort( 3, @<, X, Y ).

The first one succeeds, the second one raises an "argument `3' does not exist in [1,2,3] ..." error. My SWI-Prolog is "(threaded, 64 bits, version 8.2.4)".

P.S. No rush, I rearrenged the lists (no bother, really) and it works just fine. Still curious tho, what did I misunderstand?

Edit:

Also, sorting two element sublists by their second element doesn't raise an error. Here's a screenshot and the query:

X = [ [1,2], [4,1], [3,5] ], sort( 2, @<, X, Y ).

Solution

  • A list, which is a compound term, only have two arguments (the list head and the list tail), not to be confused with the list elements. The following arg/3 queries should help understand that error:

    ?- arg(1, [1,2,3], Arg1).
    Arg1 = 1.
    
    ?- arg(2, [1,2,3], Arg2).
    Arg2 = [2, 3].
    
    ?- arg(3, [1,2,3], Arg3).
    false.