Olga Anastasiadou
Olga Anastasiadou

Reputation: 143

sorting list of lists by the second element of each sublist prolog

I have a list like L = [[id1,avg1],[id2,avg2],....,[idN,avgN]] and I want to sort this list by avg. I can't even start coding! Any idea???

Upvotes: 1

Views: 2517

Answers (1)

Mark Bolusmjak
Mark Bolusmjak

Reputation: 24409

You probably want to look into predsort. For this you need to create a predicate that does comparisons for your list items.
For example:

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

then you can call

predsort(compareAvg, [[1,2],[3,1],[5,3]],X).

Upvotes: 7

Related Questions