I have an assignment in prolog with lists and before anything else i have to order the list based on the second element.
The list is a code, for example, this
[(a,[1,0]),(x,[0,0]),(d,[0,1])] has to be [(x,[0,0]),(d,[0,1]),(a,[1,0])] because it's sorted based on the binary code. Right now I'm just using sort/2 but it sorts the list based on the first caracter like this [(a,[1,0]),(d,[0,1]),(x,[0,0])] which is wrong.
I'm inexperienced in prolog so maybe there's a way to do this with sort/2 and I don't know it?
I've also seen another question with this suggestion:
compareAvg(X, [_,A1], [_,A2]) :- compare(X, A1, A2).
then you can call
predsort(compareAvg, [[1,2],[3,1],[5,3]],X).
but my list has a varying size so I don't know how to use it.
[(a,[1]),(x,[1,1]),(d,[0,1,0])], you want to get[(a,[1]),(d,[0,1,0]),(x,[1,1])](where the code lists[1],[0,1,0]and[1,1]are interpreted as the numbers1,2and3) or[(d,[0,1,0]),(a,[1]),(x,[1,1])](where the code lists represent themselves)? If the code lists should be taken as numbers, then you will need to convert then to numbers before sorting. - slago[1]is numerically less than[0,1,0](since number 1 is less than number 2), but[0,1,0]is lexicographically less than[1](since the head of the first list, 0, is less than the head of the second list, 1). - slago?- sort(2,@=<,[(a,[1,0,1]),(x,[1]),(d,[0,1,0])], Sorted).producesSorted = [(d,[0,1,0]),(x,[1]),(a,[1,0,1])], notSorted = [(x,[1]),(d,[0,1, 0]),(a,[1,0,1])](that would be produced if code lists are interpreted as numbers). - slago