Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordering a list of lists in Haskell

Tags:

list

haskell

Say if I had a list of lists like [[1,3,4],[1,5,6,7],[2,8,0]] or ["QQQ", "RRRR", "TTTTT"] , is there a function that will order them by the number of elements in inner lists i.e. so in the Int list, the 4 element list goes to the front and in the Strings list, the Ts go to the front and then the Rs?

like image 408
James Avatar asked Oct 18 '25 00:10

James


2 Answers

Use sortBy with a custom predicate:

Prelude> import Data.List
Prelude Data.List> let l = [[1,3,4],[1,5,6,7],[2,8,0]]
Prelude Data.List> sortBy (\e1 e2 -> compare (length e2) (length e1))  l
[[1,5,6,7],[1,3,4],[2,8,0]]

Edit: Thanks @JJJ for a more beautiful variant

Prelude Data.List> import Data.Ord
Prelude Data.List Data.Ord> sortBy (flip $ comparing length) l
[[1,5,6,7],[1,3,4],[2,8,0]]
like image 83
fjarri Avatar answered Oct 20 '25 21:10

fjarri


sortBy from Data.List and comparing from Data.Ord will help you.

foo = sortBy (comparing (negate . length))

bar = foo ["QQQ", "RRRR", "TTTTT"]
like image 43
Vektorweg Avatar answered Oct 20 '25 20:10

Vektorweg