How to check if an element is present in a list 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 check if a list contains an element
We can check if a list contains a particular element by following the steps below:
- Separate the element at the head of the
listfrom the rest of thelist. - Check if the element at the head matches the element we want to find.
- If the two elements do not match, recursively perform steps 1 and 2 with the remaining list until either the element is found, or all elements within the
listhave 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"])
Explanation
In the code above:
- In line 1, we declare a function called
containsthat accepts alistand an element as arguments and returns aBool. The placeholderaindicates that thelistand element to search may be of any data type, but the data types of both thelistelements and the element to search must be the same. TheEqclass ensures that the function only accepts arguments such that the elements are comparable. - In line 2,
containstakes an element calledelemand alistcalledmyListas parameters. - In line 3, we use a
case-ofstatement to check different cases formyList. - Line 4 defines the base case for the recursive function. If
myListis empty, thenelemcannot be present in the list, so the function returnsFalse. - Otherwise, in line 5,
myListis split into two parts, i.e., the element at the head and the rest of the list through the expressionx:xs. Ifxmatcheselem, then we can conclude thatmyListcontainselemand the function returnsTrue. - If
xdoes not matchelem, then we need to check ifelemis present in the remaining part ofmyList. Therefore, in line 6, we make a recursive call tocontainswithelemandxsas the parameters. - We call the
containsfunction twice in line 8. The first function call checks if the element2is present in [1,2,3]. Consequently, thecontainsfunction returnsTrue. The second function call checks if the element"c"is present in["a", "b"]. Since thislistdoes not contain"c", the function returnsFalse.