【问题标题】:Haskell writing a Filter for selfdefined ListHaskell 为自定义列表编写过滤器
【发布时间】:2015-01-19 05:59:55
【问题描述】:

嘿嘿。

我现在正在大学学习 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)

【问题讨论】:

    标签: list haskell filter


    【解决方案1】:

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

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

    e : (filterList f l)
    

    Cons e (filterList f l)
    

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

    【讨论】:

    • 你的回答很快而且结构很好。谢谢你。 ;)
    【解决方案2】:

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

    (顺便说一句,这类问题的错误总是贴出来。它可能对你没有任何意义,但它往往对我们的回答有很大帮助。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-18
      • 1970-01-01
      • 2011-01-31
      • 2016-11-15
      • 2019-01-03
      • 1970-01-01
      • 2012-08-09
      相关资源
      最近更新 更多