Quicksort带有自定义过滤器

时间:2011-10-20 19:47:39

标签: haskell quicksort

我需要使用自定义过滤器进行快速排序。 在编译期间,我在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]

有什么问题?

1 个答案:

答案 0 :(得分:2)

我认为有两个问题可能让你不安。

首先,将带有定义的文件加载到ghci中,我尝试

ghci> csort (>= x) [2,1,3]

<interactive>:1:10: Not in scope: 'x'

你编写它的方式,f有两个参数。确实x不在此范围内。因此,自定义过滤器功能应该只是(>=)

ghci> csort (>=) [2,1,3]
***Exception: blahblah: Non-exhaustive patterns in function csort

现在真正的问题:非详尽的模式。这是什么意思?您已经编写了如何使用至少一个元素对列表进行排序的定义。但是如何对没有元素的列表进行排序?很简单,您忽略自定义过滤器功能,只需生成一个空列表。由于空列表没有元素,因此它已经“排序”。

csort _ [] = []

一旦我将该行添加到源文件中,它就突然起作用了。模式[]与模式(x:xs)相称,并且这两种模式一起是详尽的(列表为空,或者至少有一个元素)。

ghci> csort (>=) [2,1,3]
[1,2,3]
ghci> csort (<) [2,1,3]
[3,2,1]
ghci> quickCheck (\xs -> csort (<) xs == (reverse $ csort (>) xs))
+++ OK, passed 100 tests.

这是我的sort.hs文件:

csort _ [] = []
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]

我不知道你为什么还会有错误;这对我来说非常适合。