简体   繁体   English

如何将合并列表按升序排序?

[英]How do I sort a merged list into ascending order?

merge :: [a] -> [a] -> [a]

 merge xs     []     = xs
 merge []     ys     = ys
 merge (x:xs) (y:ys) = x : y : merge xs ys

I have got this working but now I need to sort them in ascending order. 我已经开始工作了,但是现在我需要按升序对它们进行排序。

You just need to compare x and y and decide which to add to the result first. 您只需要比较xy并确定要先添加到结果中。 Note that you only add one at a time; 请注意,一次只能添加一个 the next element after x might still come before y . x之后的下一个元素可能仍在y之前。

Note you need the Ord constraint to ensure that <= is defined for a . 注意:您所需要的Ord约束,以确保<=被定义为a

merge :: Ord a => [a] -> [a] -> [a]
merge xs [] = xs
merge [] ys = ys
merge xs@(x:xs') ys@(y:ys') | x <= y = x : merge xs' ys
                            | otherwise = y : merge xs ys'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM