How to remove a list's first element in Haskell
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 listx:xs -> xs -- split head and return remaining list-- call function to remove first element of a listmain = print(removeFirst [1,2,3], removeFirst ["a", "b"], removeFirst [3])
Explanation
- Line 1: We declare a function called
removeFirstthat accepts alistas an argument. It returns alistwith the first element removed. The placeholderaindicates that thelistmay be of any data type. - Line 2:
removeFirsttakes alist, calledmyList, as a parameter. - Line 3: We use a
case-ofstatement to check different cases formyList. - Line 4: If
myListis empty, then the function returns the emptylist. - Line 5: Otherwise,
myListis split into two parts through the expressionx:xs.xrepresents the first element ofmyList, whereasxsrepresents the rest ofmyList. Consequently, theremoveFirstfunction returnsxs. - Line 8: The
removeFirstfunction is called thrice. Each function call removes the first elements of thelists[1,2,3],["a", "b"], and[3], respectively. The modifiedlistsare shown as output accordingly.