Int positiveSum (x) = 0 positiveSum (x:xs) = r-6ren">
gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 08:29:23 25 4
gpt4 key购买 nike

这是我的代码:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com