我正试图按每匹马的高度按升序快速排序。例如[("Thunder",125),("Lightning",115),("Bolt",135)]。
我试过以下方法;
type Horse = (String, Int)
sort_horse_list :: [Horse] -> [Horse]
sort_horse_list horses = quick_sort horses
(h1 h2 -> snd h1 <= snd h2)
期望输出为[("Lightning",115),("Thunder",125),("Bolt",135)]。
我不知道你使用的是什么类型的quick_sort
函数,因为已经被left - roundabout评论过了。如果不知道你正在使用的快速排序算法的类型,很难给你一个确切的答案。然而,我确实使用sortBy
和comparing
函数创建了一个实现。sortBy
函数不使用快速排序(它使用归并排序),所以如果您必须使用快速排序,这不是一个有效的解决方案:
import Data.List
import Data.Ord
type Horse = (String, Int)
sort_horse_list :: [Horse] -> [Horse]
sort_horse_list = sortBy (comparing $ snd)
可以这样使用:
main :: IO ()
main = let xs = [("Thunder",125),("Lightning",115),("Bolt",135)] in do
print (sort_horse_list xs)