Home > Net >  Compare list of lists in Haskell
Compare list of lists in Haskell

Time:05-22

Supposing my list defined as [[Id, time, priority] , [Id, time, priority], [Id, time, priority] ... ]

In This exemple, i want to order my lists in an increasing way depending on the priorities and if I have two equal priorities I order them depending on the time (whoever has the greatest time comes first):

From this : [["43525", "5", "2"],["25545", "7", "5"],["7455", "3", "4"],["3586", "8", "2"]]

To this : [[3586, 8, 2], [43525, 5, 2], [7455, 3, 4], [25545, 7, 5]]

First, I convert all the strings to Int using read fucntion and mapping on all elements :

map (map (read :: String -> Int)) [["43525", "5", "2"],["25545", "7", "5"],["7455", "3", "4"],["3586", "8", "2"]]

CodePudding user response:

You can define custom sort function and use sortBy from Data.List:

import Data.List

toSort = map (map (read :: String -> Int)) [["43525", "5", "2"],["25545", "7", "5"],["7455", "3", "4"],["3586", "8", "2"]]
sortLGT x y = compare (x!!2) (y!!2) -- compare priorities 
    <> compare (y!!1) (x!!1) -- compare time in descending order

sortBy sortLGT toSort

Output:

[[3586,8,2],[43525,5,2],[7455,3,4],[25545,7,5]]

Or as @Daniel Wagner suggests in the comments, use sortOn, which should be better option:

sortOn (\[_id, time, prio] -> (prio, Data.Ord.Down time)) toSort
  • Related