Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading