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 String
s list, the T
s go to the front and then the R
s?
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]]
sortBy
from Data.List and comparing
from Data.Ord will help you.
foo = sortBy (comparing (negate . length))
bar = foo ["QQQ", "RRRR", "TTTTT"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With