我昨晚刚开始学习 Haskell,以前从未使用过函数式编程语言。我只想知道我的合并排序实现是好是坏,究竟是好是坏。也许它甚至是错误的 - 它确实排序但也许算法不是我认为的合并排序。
只要告诉我我可以在这里改进的一切。我自己认为这是一个非常清晰和简单的实现。感谢您的建议,这是代码:)
merge [] ys = ys
merge xs [] = xs
merge xs ys = sorted : merge left right
where
sorted = if head(xs) < head(ys) then head(xs) else head(ys)
left = if head(xs) <= head(ys) then tail(xs) else xs
right = if head(xs) > head(ys) then tail(ys) else ys
msort [] = []
msort [x] = [x]
msort xs = merge (msort left) (msort right)
where
left = take (div (length xs) 2) xs
right = drop (div (length xs) 2) xs