为什么使用null函数而不是== []检查Haskell中的空列表? [英] Why use null function instead of == [] to check for empty list in Haskell?
问题描述
我正在阅读 学习Haskell的伟大成就的"Starting Out"一章! .它说:
I am reading through the "Starting Out" chapter of Learn You a Haskell for Great Good!. It says:
null
检查列表是否为空.如果是,则返回True
,否则返回False
.使用此功能代替xs == []
(如果您有一个名为xs
的列表)
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
)
我在ghci中尝试过
xs = [] -- and then,
xs == []
null xs
他们都是True
.
我想知道有什么区别.
I wonder what's the difference.
我应该使用null
函数而不是== []
吗?
Should I use the null
function instead of == []
and why?
推荐答案
您应使用null
.在大多数情况下,这并不重要,但是无论如何这都是一个好习惯,因为有时候您可能想检查一系列不可比的事物是否为空.这是一个简短而清晰的示例,显示了这种差异:
You should use null
. In most cases it doesn't matter, but it is a good habit to get into anyway, because occasionally you may want to check if a list of non-comparable things is empty. Here is a short, crisp example showing this difference:
> null [id]
False
> [id] == []
<interactive>:1:1: error:
• No instance for (Eq (a0 -> a0)) arising from a use of ‘==’
(maybe you haven't applied a function to enough arguments?)
• In the expression: [id] == []
In an equation for ‘it’: it = [id] == []
这篇关于为什么使用null函数而不是== []检查Haskell中的空列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!