I have just started to learn Haskell out of interest. I follow learnyouahaskell.com.
There I found this:
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
)
Why is that? Why should we use null
instead of ==
when both produce the same result?
Thanks.
equals(null) will always be false. The program uses the equals() method to compare an object with null . This comparison will always return false, since the object is not null .
7. == and != The comparison and not equal to operators are allowed with null in Java.
Null means nothing. No object. At all. A null value can be assigned to an object reference of any type. Null can be cast to any type as it can be assigned to an object reference of that type.
null means that a variable contains a reference to a space in memory that does not contain an object. 0 is a numeric data type with a value of 0. Nothing doesn't really exist, however I think you may be viewing this as an empty String "" which is simply a String data type that does not contain a value.
Comparing the lists with ==
requires elements to be comparable (denoted as Eq a
).
Prelude> :t (==[])
(==[]) :: (Eq a) => [a] -> Bool
For example, [sin] == []
won't work, since you can't compare functions. It might seem stupid, but the type system must judge type of an expression without looking at its value.
An alternate check would be length xs == 0
, this doesn't require equality but won't stop if your list is infinite (try length [1..] == 0
). That's why there's a dedicated function.
null [] = True
null _ = False
Prelude> :t null
null :: [a] -> Bool -- Notice lack of (Eq a).
In my opinion, null myList
reads more naturally than myList == []
.
But the raison d'être for null
is that it can be used as a function. For example, here's a function that takes a list of lists, and returns only the nonempty ones:
nonemptyLists :: [[a]] -> [[a]]
nonemptyLists = filter (not . null)
Without null
, this would be more awkward:
nonEmptyLists = filter ([] /=)
Another benefit to using null
is that many other containers (e.g. Data.Sequence, Data.ByteString, etc.) have a null
function as well. This makes it easy to switch to another implementation simply by changing your import statements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With