Share
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
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])
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.removeFirst
takes a list
, called myList
, as a parameter.case-of
statement to check different cases for myList
.myList
is empty, then the function returns the empty list
.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
.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.