I am trying to create an empty list then confirm that it is empty so I can later on insert elements into it.
I tried to simply assign the function to an empty list but when i try to confirm that it is empty I get an Non-exhaustive patterns in function exception.
Here is what I have so far.
emptyList::Ord a => [(a,b)]
emptyList = []
isEmpty::Ord a => [(a,b)] -> Bool
isEmpty[(a,b)] = null [undefined, undefined]
I am trying to get something like
isEmpty emptyList
True
I guess my question here is that, how can I confirm that the list is empty based on the given type?
I think you are confusing the type ([(a,b)]
) with the patterns. In your isEmpty
function, you write:
isEmpty::Ord a => [(a,b)] -> Bool
isEmpty [(a,b)] = null [undefined, undefined]
But this does not mean that you are going to match lists of type [(a,b)]
. You already said that in your type signature. Your [(a,b)]
in the second line, means you define a pattern. The pattern sayd that you are only matching lists that contain exactly one element: a 2-tuple, with a
the first item of that tuple, and b
the second item of that tuple.
If you then pass it an empty list, or a list with two or more elements, then the pattern will not match, and hence it will raise an error.
If you want to match any list, you can simply use a variable:
isEmpty :: Ord a => [(a,b)] -> Bool
isEmpty ls = null ls
here isEmpty
thus will call null
with that variable. We can perform an η-reduction here, and write:
isEmpty :: Ord a => [(a,b)] -> Bool
isEmpty = null
There is no need at all, to restrict ourselves to only lists with 2-tuples where the first item of these tuples has a type that is a member of the Ord
typeclass however, we can let this work with any list. So we can generalize the type to:
isEmpty :: [a] -> Bool
isEmpty = null
In fact null
can operate over any Foldable
, since it has type null :: Foldable f => f a -> Bool
.
Given the above function defintion, there is no need to implement your own isEmpty
, you can simply call null emptyList
.