使用自定义过滤器进行快速排序
我需要使用自定义过滤器进行快速排序。 在编译期间,我在 filter (>=x) xs
上收到错误。
--sort with two filters
quicksort (x:xs) = (quicksort lesser) ++[x] ++ (quicksort greater)
where lesser = filter (<x) xs
greater = filter (>=x) xs
--sort with custom filter
csort f (x:xs) = (csort f lesser) ++ [x] ++ (csort f greater)
where lesser = [e | e <- xs, f x e]
greater = [e | e <- xs, not $ f x e]
怎么了?
I need to make quicksort but with a custom filter.
During compilation I get an error on filter (>=x) xs
.
--sort with two filters
quicksort (x:xs) = (quicksort lesser) ++[x] ++ (quicksort greater)
where lesser = filter (<x) xs
greater = filter (>=x) xs
--sort with custom filter
csort f (x:xs) = (csort f lesser) ++ [x] ++ (csort f greater)
where lesser = [e | e <- xs, f x e]
greater = [e | e <- xs, not $ f x e]
What is wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为有两个问题可能困扰着您。
首先,将包含您的定义的文件加载到ghci中,我尝试
按照您编写的方式,
f
采用两个参数。事实上,x
不在此处的范围内。所以自定义过滤器函数应该是简单的(>=)
。现在真正的问题是:非详尽的模式。这意味着什么?您已经编写了如何对至少包含一个元素的列表进行排序的定义。但是如何对没有元素的列表进行排序呢?很简单,您忽略自定义过滤器功能,并简单地生成一个空列表。由于空列表没有元素,因此它已经“排序”。
一旦我将该行添加到源文件中,它就突然起作用了。模式
[]
与模式(x:xs)
相得益彰,这两个模式一起是详尽的(列表要么是空的,要么至少有一个元素)。这是我的 sort.hs 文件:
我不知道为什么你仍然会出现错误;这对我来说非常有效。
There are two problems I think might be troubling you.
First of all, loading a file with your definitions into ghci, I try
The way you wrote it,
f
takes two parameters. And indeedx
is not in scope here. So the custom filter function should be simply(>=)
.Now the real problem: non-exhaustive patterns. What does this mean? You've written a definition of how to sort a list with at least one element. But how do you sort a list with no elements? Simple, you ignore the custom filter function, and simply produce an empty list. Since an empty list has no elements, it is already "sorted".
Once I added that line to the source file, it suddenly worked. The pattern
[]
compliments the pattern(x:xs)
, and those two patterns, together, are exhaustive (a list is either empty, or it has at least one element).Here's my sort.hs file:
I have no idea why you would still have errors; this works perfectly well for me.