Home > Mobile >  Decide if the first parameter's list contains elements in the second parameter's list
Decide if the first parameter's list contains elements in the second parameter's list

Time:11-06

Define the

listCheck :: [[Char]] -> [[Char]] -> Bool

function that decides whether the first parameter's list of words contains a word that is also in the second parameter's list. We can assume that both lists only contain lowercase letters. If at least one of the parameters is an empty list, then return False.

For example:

listCheck ["hey", "hello", "hi"] ["whatsup", "hi"] == True
listCheck ["hey", "hello", "hi"] ["whatsup"] == False

So far, I've tried:

listCheck [] _ = False
listCheck _ [] = False    
listCheck (x:xs) [y]
  | x == y = True
  | otherwise = listCheck (xs) [y]

Which does what I expected. It only checks for the first element of the second parameter (it always returns the correct value if the second list has only one element, so at least I got that right). I don't know how to implement the recursion for the rest of the second lists' elements.

CodePudding user response:

listCheck :: [[Char]] -> [[Char]] -> Bool
listCheck [] _ = False
listCheck (x:xs) ys = go x ys || listCheck xs ys where
   go _ [] = False
   go x (y:ys)
     | x == y = True
     | otherwise = go x ys

We use a helper function go to compare one element from one list with all the elements from the other list. If an element x is not found in the list ys, we try the rest of xs on ys. || guarantees that the function returns as soon as a match is found without checking the rest. Finally, if xs is exhausted we can be sure that there is no match and return False.

  • Related