假設我的串列定義為[[Id, time, priority] , [Id, time, priority], [Id, time, priority] ... ]
在這個例子中,我想根據優先級以遞增的方式排列我的串列,如果我有兩個相同的優先級,我會根據時間對它們進行排序(時間最長的人先到):
由此 :
[["43525", "5", "2"],["25545", "7", "5"],["7455", "3", "4"],["3586", "8", "2"]]
對此:
[[3586, 8, 2], [43525, 5, 2], [7455, 3, 4], [25545, 7, 5]]
首先,我使用讀取功能和所有元素上的映射將所有字串轉換為 Int :
map (map (read :: String -> Int)) [["43525", "5", "2"],["25545", "7", "5"],["7455", "3", "4"],["3586", "8", "2"]]
uj5u.com熱心網友回復:
您可以定義自定義排序功能并使用sortByfrom 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
輸出:
[[3586,8,2],[43525,5,2],[7455,3,4],[25545,7,5]]
或者正如@Daniel Wagner在評論中建議的那樣,使用sortOn,這應該是更好的選擇:
sortOn (\[_id, time, prio] -> (prio, Data.Ord.Down time)) toSort
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/479390.html
標籤:哈斯克尔
上一篇:如何在Haskell中使用遞回
