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] -> Bool
isEmpty = \myList ->
case myList of
[] -> True -- if the list is empty, return true
_ -> False -- otherwise, return false
-- call function to check if different lists are empty
main = print(isEmpty [1,2,3], isEmpty ["a"], isEmpty [])

Explanation

In the code above:

  • In line 1, we declare a function called isEmpty that accepts a list as an argument and returns a Bool. The placeholder a indicates that the list may be of any data type.
  • In line 2, isEmpty takes a single list as a parameter.
  • In line 3, we use a case-of statement to check whether or not myList is an empty list.
  • If myList is empty, then the function returns True in line 4; otherwise, it returns False in line 5.
  • In line 8, we call the isEmpty function thrice, with a different list each time. The first two calls to isEmpty involve lists that are not empty, i.e., [1,2,3] and ["a"], so it returns False for both. The final call to isEmpty uses an empty list as the parameter, so the function returns True.

Free Resources