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

Trying to match components in a pair

lookUp :: Char -> [(Char, Char)] -> Char
lookUp x xs = [if x `elem` xs then tail(xs) else head(xs) | x <- xs]

There is a type error but I’m not sure why. I’m trying to find the first component of the pair and return the second component, or return x if the input isn’t part of a pair.

>Solution :

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

x is a Char, while xs is meant to be a list of (Char, Char) tuples. The elem function has the following type, so yes, you will get a type error.

elem :: (Foldable t, Eq a) => a -> t a -> Bool

This function makes more sense returning Maybe Char, as the key you’re searching for may not exist in the list. We know the key won’t exist in an empty list. Otherwise we can recursively iterate over the list testing each tuple as we go.

lookup :: Char -> [(Char, Char)] -> Maybe Char
lookup _ [] = Nothing
lookup ch ((x, ch'):xs) 
  | ch == x =   -- fill in the blanks
  | otherwise = -- fill in the blanks 
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