In addition to the good answers given so far, null
actually has type
null :: Foldable t => t a -> Bool
I don't know if you've gotten to typeclasses in LYAH, but the short of it is that null
can be used not just for lists, but for any data structure that implements null
.
This is to say that using null
on a Map
or a Set
is valid, too.
> null Map.empty
True
> null (Map.singleton 1)
False
> null Set.empty
True
> null (Set.singleton 1)
False
> null []
True
> null [1]
False
I don't think it's especially common to write functions that need to be this general, but it doesn't hurt to default to writing more general code.
A side note
In many cases, you'll end up wanting to use a function like null
to do conditional behavior on a list (or other data structure). If you already know that your input is a specific data structure, it's more elegant to just pattern match on its empty case.
Compare
myMap :: (a -> b) -> [a] -> [b]
myMap f xs
| null xs = []
myMap f (x:xs) = f x : myMap f xs
to
myMap' :: (a -> b) -> [a] -> [b]
myMap' f [] = []
myMap' f (x:xs) = f x : myMap' f xs
In general, you should try to prefer pattern matching if it makes sense.