在我的程序上运行 hlint 时,它报告了 错误 为了
\x -> [x]
并提出了另一种形式
(: [])
有什么错误根据关于第一种形式的 hlint,因此我为什么要使用(可读性较差的)第二个选项?
编辑
(在问题中明确添加了 hlint)
我的问题不在于从词汇的角度来看有什么区别(我确实理解它们)。我的问题是我不明白为什么 hlint 将其标记为 错误 .例如,懒惰有区别吗?此外,为什么以前的想法是 错误通过 hlint 而
\x -> Just x
只发出警告。
最佳答案
一个常见问题,我刚刚在 HLint manual 中添加了一个答案.它说:
Every hint has a severity level:
- Error - for example
concat (map f x)
suggestsconcatMap f x
as an "error" severity hint. From a style point of view, you should always replace a combination ofconcat
andmap
withconcatMap
. Note that both expressions are equivalent - HLint is reporting an error in style, not an actual error in the code.- Warning - for example
x !! 0
suggestshead x
as a "warning" severity hint. Typicallyhead
is a simpler way of expressing the first element of a list, especially if you are treating the list inductively. However, in the expressionf (x !! 4) (x !! 0) (x !! 7)
, replacing the middle argument with head makes it harder to follow the pattern, and is probably a bad idea. Warning hints are often worthwhile, but should not be applied blindly.The difference between error and warning is one of personal taste, typically my personal taste. If you already have a well developed sense of Haskell style, you should ignore the difference. If you are a beginner Haskell programmer you may wish to focus on error hints before warning hints.
虽然区别在于个人品味,但有时我会改变主意。查看此线程中的两个示例,
(:[])
似乎是一个相对“复杂”的提示 - 您正在分解 [x]
的语法糖至x:[]
,如果您从不对其进行模式匹配,那么它在某些方面将列表的抽象剥离为通用容器。相比之下\x -> Just x
至Just
似乎总是一个好主意。因此,在 HLint-1.8.43(刚刚发布)中,我将第一个警告,第二个错误。
关于haskell - 创建单例列表的两个函数之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14530555/