Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a list of lists by the seconds element

I'm having a hard time when I try to order a list of lists by the second element, something like this

list = [[_,B,_,_,_],[_,A,_,_,_],[_,C,_,_,_]]

into this:

list = [[_,A,_,_,_],[_,B,_,_,_],[_,C,_,_,_]]

I've tried:

sortBy compare $ [([1,2]!!1),([2,3]!!1)]

But it filters the seconds elements and order that into [2,3].

like image 475
seph Avatar asked Jan 07 '12 20:01

seph


1 Answers

What you tried to do is sort the list [([1,2]!!1),([2,3]!!1)], which is equivalent to [2, 3], by compare. What you want to do is use sortBy with a function that first gets the second element and then compares:

sortBySecond = sortBy (\ a b -> compare (a !! 1) (b !! 1))

Then take the list you have and apply this function to it:

sortBySecond [[1, 2], [2, 3]]

You can make this function neater by using on from Data.Function:

import Data.Function

sortBySecond = sortBy (compare `on` (!! 1))

You can also use comparing from Data.Ord:

sortBySecond = sortBy $ comparing (!! 1)
like image 64
Tikhon Jelvis Avatar answered Sep 28 '22 18:09

Tikhon Jelvis