首页 文章

从列表中过滤出空列表

提问于
浏览
1

考虑清单

[[],[1],[1,2],[1,2,3],[],[2],[2,3],[],[3],[]]

我想过滤掉所有非空列表的元素,即过滤后的输出应该给我一个结果,如:

[[1],[1,2],[1,2,3],[2],[2,3],[3]]

以下代码失败:

myfilter lst = filter(\x -> x/=[]) lst

[12,3,[]]出现以下错误

No instance for (Num [a])
  arising from the literal `3' at <interactive>:1:13
Possible fix: add an instance declaration for (Num [a])
In the expression: 3
In the first argument of `myfilter', namely `[12, 3, []]'
In the expression: myfilter [12, 3, []]

1 回答

  • 16

    你的功能看起来不错,但是:

    myfilter [12, 3, []]
    

    ...是类型错误 . 列表包含同类型的值,而您在此处放置了数字和空列表 .

    我希望你想要的是 [[12], [3], []] .

    在GHCi中:

    > myfilter [[12], [3], []]
    [[12],[3]]
    

    ......这似乎正是你想要的 .


    对于将来,参考,您获得的错误的翻译密钥:

    No instance for (Num [a])
    

    这意味着它尝试并失败,为类型 [a] 找到 Num 的实例 . 我们不希望这个实例存在,所以问题出在其他地方 .

    arising from the literal `3' at <interactive>:1:13
    

    Num 类型类包含 fromInteger ,用于将数字文字(如 3 )转换为某种特定类型 . 所以这告诉我们的是,它在一个上下文中找到 3 ,它预期类型为 [a] ,并尝试使用 fromInteger . 这导致上面的"no instance"错误 .

    Possible fix: add an instance declaration for (Num [a])
    

    这条线是无稽之谈 . 缺少 Num 实例导致的错误几乎不会因忘记编写合理的实例声明而导致 .

    In the expression: 3
    

    这告诉我们发现错误的表达式 . 不过,我们已经知道了这一点,因为之前提到了文字 3 .

    In the first argument of `myfilter', namely `[12, 3, []]'
    

    错误表达式的更多上下文,这是我们最终可以发现问题的地方:由于列表具有同源类型,给定 12123 ,以及 [a] 类型的 [] ,它们统一得到 Num [a] => [a] ,导致错误 . 在这种情况下的修复是我上面所说的, [[12], [3], []] 具有(正确的)类型 Num a => [[a]] .

相关问题