list - "Pattern match is redundant"在列表推导中使用输入列表参数时

标签 list function haskell list-comprehension

这是我的代码:

example = [1,-4,7,12]

positiveSum :: [Int] -> Int
positiveSum (x) = 0
positiveSum (x:xs) = result
  where 
    result = sum [y+y | y <- xs, y > 0]

main = do
  print (positiveSum example)

当我运行它时,我得到:

Main.hs:5:1: warning: [-Woverlapping-patterns]
    Pattern match is redundant
    In an equation for `positiveSum': positiveSum (x : xs) = ...
  |
5 | positiveSum (x:xs) = result
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^...

我不能在列表理解中使用“xs”,我不明白为什么。这是一个引用,我应该可以使用它。为什么它是多余的?

编辑:

答案解决了问题,我正在将任何内容与第一个 (x) 匹配。另外,我把自己弄糊涂了,两次应用 sum 。这是正确的代码:

positiveSum :: [Int] -> Int
positiveSum [] = 0
positiveSum xs = result
  where 
    result = sum [x | x <- xs, x > 0]

最佳答案

你似乎认为 positiveSum (x) = 0 只会匹配空列表的情况,但实际上它会匹配任何东西,这使得下一行变得多余,因为它永远不会被尝试.你打算在那里写 positiveSum [] = 0。另外,请注意您的第二个案例,即使它现在会运行,也会丢弃列表的头部,您可能并不想这样做。

关于list - "Pattern match is redundant"在列表推导中使用输入列表参数时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70842746/

相关文章:

haskell - 关于优化 GHC 中单构造函数数据类型的说明

haskell - 如何获取 `ghci` 来使用我的 `show` 函数?

haskell - 基本 haskell : list comprehension for copying an element n times

java - Java中队列链表中的递归toString

python - 如何检查日期是否在日期字符串列表中?

Python:如何将两个列表列表合并在一起,避免重复?

Python - 通过计算从列表创建元组的最快方法

c - 初学C循环函数

java - 无法调用我的字符串函数

C - 变量 'name' 周围的堆栈已损坏