出于兴趣,我刚刚开始学习 Haskell。我关注 learnyouahaskell.com .
在那里我发现了这个:
null
checks if a list is empty. If it is, it returnsTrue
, otherwise it returnsFalse
. Use this function instead ofxs == []
(if you have a list calledxs
)
这是为什么?为什么要使用
null
而不是 ==
当两者产生相同的结果时?谢谢。
最佳答案
将列表与 ==
进行比较要求元素具有可比性(表示为 Eq a
)。
Prelude> :t (==[])
(==[]) :: (Eq a) => [a] -> Bool
例如,
[sin] == []
行不通,因为您无法比较功能。这可能看起来很愚蠢,但类型系统必须在不查看表达式的值的情况下判断表达式的类型。另一种检查是
length xs == 0
,这不需要相等,但如果您的列表是无限的,则不会停止(尝试 length [1..] == 0
)。这就是为什么有一个专门的功能。null [] = True
null _ = False
Prelude> :t null
null :: [a] -> Bool -- Notice lack of (Eq a).
关于haskell - null 而不是 ==,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3853922/