大家好,我正在尝试在 haskel 中重现合并排序,这是我的代码:
-- merge
merge :: (Ord a) => [a] -> [a] -> [a]
merge [] [] = []
merge xs [] = xs
merge [] ys = ys
merge (x:xs) (y:ys)
| x <= y = x:(merge xs (y:ys))
| otherwise = y:(merge (x:xs) ys)
-- split
splitIn2 :: (Ord a) => [a] -> ([a],[a])
splitIn2 [] = ([],[])
splitIn2 xs = splitAt ((length xs `div` 2)+1) xs
-- msort
msort :: (Ord a) => [a] -> [a]
msort [] = []
msort [x] = [x]
msort (xs) = merge (msort as) (msort bs)
where (as,bs) = splitIn2 xs
它在 ghc 上编译,适用于:
*Main> msort([])
[]
*Main> msort([1])
[1]
然而它不能正确地完成它的工作,因为它开始无限循环(至少这是我的想法)并且它不打印任何东西。
我认为这是因为我没有像在其他递归实验中那样从列表中删除元素,有什么建议吗?