How to check if a list is empty in Haskell
What are lists?
In Haskell, lists are a data structure that stores multiple items of the same type.
Syntax
[1,2,3] -- A list of integers
['a', 'b', 'c'] -- a list of characters
Example
The code below shows how to check if a list is empty.
isEmpty :: [a] -> BoolisEmpty = \myList ->case myList of[] -> True -- if the list is empty, return true_ -> False -- otherwise, return false-- call function to check if different lists are emptymain = print(isEmpty [1,2,3], isEmpty ["a"], isEmpty [])
Explanation
In the code above:
- In line 1, we declare a function called
isEmptythat accepts alistas an argument and returns aBool. The placeholderaindicates that thelistmay be of any data type. - In line 2,
isEmptytakes a singlelistas a parameter. - In line 3, we use a
case-ofstatement to check whether or notmyListis an emptylist. - If
myListis empty, then the function returnsTruein line 4; otherwise, it returnsFalsein line 5. - In line 8, we call the
isEmptyfunction thrice, with a differentlisteach time. The first two calls toisEmptyinvolveliststhat are not empty, i.e.,[1,2,3]and["a"], so it returnsFalsefor both. The final call toisEmptyuses an empty list as the parameter, so the function returnsTrue.