0
votes

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.

2
Should code lists be interpreted as numbers or lists? I mean: for example, sorting the list [(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 numbers 1, 2 and 3) 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
@slago does it make a difference? The greatest number would be achieved by sorting the lists anyway - coder
@coder Of course it does: [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
@coder Notice that ?- sort(2,@=<,[(a,[1,0,1]),(x,[1]),(d,[0,1,0])], Sorted). produces Sorted = [(d,[0,1,0]),(x,[1]),(a,[1,0,1])], not Sorted = [(x,[1]),(d,[0,1, 0]),(a,[1,0,1])] (that would be produced if code lists are interpreted as numbers). - slago
@slago, yeah you're right ! basically in my solution i assumed lists would be of same length were it works right i think.. - coder

2 Answers

2
votes

You could use the sort/4 predicate:

sort(2, @=<, Input, SortedOutput).

Examples:

?- sort(2, @=<, [(a,[1,0]),(x,[0,0]),(d,[0,1])], Sorted).
Sorted = [(x, [0, 0]),  (d, [0, 1]),  (a, [1, 0])].

?- sort(2, @=<, [(a,[1,0,1]),(x,[0,0,1]),(d,[0,1,0])], Sorted).
Sorted = [(x, [0, 0, 1]),  (d, [0, 1, 0]),  (a, [1, 0, 1])].
0
votes

You can try with

compareAvg(X,  [_,A1 | _], [_,A2 | _]) :- compare(X, A1, A2).