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
contains an elementWe can check if a list
contains a particular element by following the steps below:
list
from the rest of the list
.list
have been checked.The code below demonstrates the process:
contains :: Eq a => a -> [a] -> Boolcontains = \elem -> \myList ->case myList of[] -> False -- if all elements checked, return Falsex:xs | x == elem -> True -- If head matches elem, return True_:xs -> contains elem xs -- Check for element membership in remaining list-- call function to check if a list contains an elementmain = print(contains 2 [1,2,3], contains "c" ["a", "b"])
In the code above:
contains
that accepts a list
and an element as arguments and returns a Bool
. The placeholder a
indicates that the list
and element to search may be of any data type, but the data types of both the list
elements and the element to search must be the same. The Eq
class ensures that the function only accepts arguments such that the elements are comparable.contains
takes an element called elem
and a list
called myList
as parameters.case-of
statement to check different cases for myList
.myList
is empty, then elem
cannot be present in the list, so the function returns False
.myList
is split into two parts, i.e., the element at the head and the rest of the list through the expression x:xs
. If x
matches elem
, then we can conclude that myList
contains elem
and the function returns True
.x
does not match elem
, then we need to check if elem
is present in the remaining part of myList
. Therefore, in line 6, we make a recursive call to contains
with elem
and xs
as the parameters.contains
function twice in line 8. The first function call checks if the element 2
is present in [1,2,3
]. Consequently, the contains
function returns True
. The second function call checks if the element "c"
is present in ["a", "b"]
. Since this list
does not contain "c"
, the function returns False
.