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

Haskell writing a Filter for selfdefined List

嘿嘿。

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

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)

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

(对了,这种问题总是post错误,可能对你没什么意义,但往往对我们的回答有很大帮助。)

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

要解决这个问题,只需更改

e : (filterList f l)

Cons e (filterList f l)

因为您希望它 return 您的 "non-standard" 列表类型。