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
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 )
removeFirstthat accepts a
listas an argument. It returns a
listwith the first element removed. The placeholder
aindicates that the
listmay be of any data type.
myList, as a parameter.
case-ofstatement to check different cases for
myListis empty, then the function returns the empty
myListis split into two parts through the expression
xrepresents the first element of
xsrepresents the rest of
myList. Consequently, the
removeFirstfunction is called thrice. Each function call removes the first elements of the
["a", "b"], and
, respectively. The modified
listsare shown as output accordingly.
View all Courses