Haskell - 合并排序,对单词和数字进行排序
我在 Haskell 中编写了一个合并排序,它在使用数字时有效,但在使用单词时无效,我认为它会。当使用单词和字母时,我只是得到“不在范围内”。我做错了什么?
这是我的代码:
merge :: Ord a => [a] -> [a] -> [a]
merge [] ys = ys
merge xs [] = xs
merge (x:xs) (y:ys)
| x <= y = x : merge xs (y:ys)
| otherwise = y : merge (x:xs) ys
mergeSort :: Ord a => [a] -> [a]
mergeSort [] = []
mergeSort [x] = [x]
mergeSort xs
= merge (mergeSort top) (mergeSort bottom)
where
(top, bottom) = splitAt (length xs `div` 2) xs
I've written a merge sort in Haskell, it works when using numbers but not with words, and I thought it would. I just get "Not in scope" when using words and letters. What am I doing wrong?
Here's my code:
merge :: Ord a => [a] -> [a] -> [a]
merge [] ys = ys
merge xs [] = xs
merge (x:xs) (y:ys)
| x <= y = x : merge xs (y:ys)
| otherwise = y : merge (x:xs) ys
mergeSort :: Ord a => [a] -> [a]
mergeSort [] = []
mergeSort [x] = [x]
mergeSort xs
= merge (mergeSort top) (mergeSort bottom)
where
(top, bottom) = splitAt (length xs `div` 2) xs
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你是这样输入文字的吗?
语法不正确。如果您想输入文字字符串,则必须将其封装在双引号中(
"
):如果这不是您的错误,请随意忽略此答案。
Are you entering your words like this?
The syntax is not correct. If you want to input a literal string, you have to encapsulte it in double quotes (
"
):If that is not your error, feel free to ignore this answer.
你的代码工作正常。
不过,我建议一次性拆分列表,而不使用
length
。当然,这里的顺序并不重要,只是我们有两个大小大致相同的列表。你可以这样做:... 或尾递归 ...
... 或使用索引 ...
... 或使用折叠 ...
Your code works fine.
However I'd suggest to split the list in one pass, without using
length
. Of course, the order isn't important here, just that we have two lists of about the same size. You could do it that way:... or tail recursive ...
... or using indexes ...
... or using a fold ...