这是我的实施:
mergesort :: (Ord a) => [a] -> [a]
mergesort list = merge (mergesort (left list)) (mergesort (right list))
where
left xs = take (div (length xs) 2) xs
right xs = drop (div (length xs) 2) xs
merge [] ys = ys
merge xs [] = xs
merge (x:xs) (y:ys)
| x <= y = x : merge xs (y:ys)
| otherwise = y : merge (x:xs) ys
代码编译但是当我运行它时我的机器崩溃了。我做错了什么?
答案 0 :(得分:3)
您缺少基本案例 - 因此您可以获得无限递归。尝试使用[]
或[1]
等列表逐步完成您的示例,您将直接陷入问题。
mergesort :: (Ord a) => [a] -> [a]
mergesort [] = [] -- < ADDED
mergesort [x] = [x] -- < ADDED
mergesort list = merge (mergesort (left list)) (mergesort (right list))
where
left xs = take (div (length xs) 2) xs
right xs = drop (div (length xs) 2) xs
merge [] ys = ys
merge xs [] = xs
merge (x:xs) (y:ys)
| x <= y = x : merge xs (y:ys)
| otherwise = y : merge (x:xs) ys