Haskell为自定义列表编写过滤器

时间:2015-01-18 21:54:05

标签: list haskell filter

Heyho。

我正在大学学习Haskell。有一项任务我无法绕过头脑。我不明白为什么这不会编译。希望可以有人帮帮我。 他们给了我们一个自定义列表,现在我们应该创建与此列表一起使用的过滤器,就像从围兜中过滤一样。 这是代码:

data List a = Nil | Cons a (List a) deriving Show

list :: List Int
list = Cons (-3) (Cons 14 (Cons (-6) (Cons 7 (Cons 1 Nil))))

filterList :: (a -> Bool) -> List a -> List a
filterList f Nil = Nil
filterList f (Cons e l) | f e = e : (filterList f l)
                        | otherwise = (filterList f l)

2 个答案:

答案 0 :(得分:4)

您对第一种情况的递归调用是错误的:您想要Cons e (filterList f l),但实际上使用的是(:),而不是Cons。原因是e : (filterList f l)的类型为[a],但实际上您需要List a

要解决此问题,只需更改

即可
e : (filterList f l)

Cons e (filterList f l)

因为您希望它返回“非标准”列表类型。

答案 1 :(得分:2)

e : (filterList f l)不是List a,而是[a],而是使用Cons e (filterList f l)

(顺便说一句,总是发布这类问题的错误。它可能对你没什么意义,但它通常会帮助我们回答。)