How to remove a list's first element in Haskell

Share

What is a list?

In Haskell, a list is a data structure that stores multiple items of the same type. Haskell lists are implemented as linked lists:

[1,2,3] -- A list of integers
['a', 'b', 'c'] -- a list of characters

How to remove the first element of a list

We can use the : operator to split the list into two parts — the head and the remaining list. The code below demonstrates how to remove the first element of a list in Haskell:

removeFirst :: [a] -> [a]
removeFirst = \myList ->
case myList of
[] -> [] -- if the list is empty, return empty list
x:xs -> xs -- split head and return remaining list
-- call function to remove first element of a list
main = print(removeFirst [1,2,3], removeFirst ["a", "b"], removeFirst [3])

Explanation

  • Line 1: We declare a function called removeFirst that accepts a list as an argument. It returns a list with the first element removed. The placeholder a indicates that the list may be of any data type.
  • Line 2: removeFirst takes a list, called myList, as a parameter.
  • Line 3: We use a case-of statement to check different cases for myList.
  • Line 4: If myList is empty, then the function returns the empty list.
  • Line 5: Otherwise, myList is split into two parts through the expression x:xs. x represents the first element of myList, whereas xs represents the rest of myList. Consequently, the removeFirst function returns xs.
  • Line 8: The removeFirst function is called thrice. Each function call removes the first elements of the lists [1,2,3], ["a", "b"], and [3], respectively. The modified lists are shown as output accordingly.