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

How can I fix my inserPair haskell code to work for all of the tests?

Specify the function that inserts a new pair into a list of key-value pairs. If the key to be inserted is already in the list, the corresponding value will be overwritten, if not, the pair will be appended to the end of the list.
It is not wworking for case 2. Can anybody help me what I have to change there to fix my code ?

insertPair :: Eq a => (a,b) -> [(a,b)] -> [(a,b)]
insertPair (a,b) [] =[(a,b)] -- case 1
insertPair (a,b) ((c,d):xs) 
 | a == c = [(c,b)] --case 2
 | otherwise = ((c,d):xs) ++ [(a,b)] --case 3 
insertPair (5,"haskell") [(0,"c++"),(5,"python"),(4,"rust")] == [(0,"c++"),(5,"haskell"),(4,"rust")]
insertPair (3,"haskell") [(0,"c++"),(5,"python"),(4,"rust")] == [(0,"c++"),(5,"python"),(4,"rust"),(3,"haskell")]
insertPair (4,"go") [] == [(4,"go")]
insertPair ('b',False) [('a',False), ('b',True)] == [('a',False), ('b',False)]
insertPair ('b',False) [('a',False)] == [('a',False), ('b',False)]

>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

The third case makes no sense: it is still possible that the key occurs further in the rest of the list xs. You thus should recurse on that list. The second case should also add xs as tail: the list of remaining elements:

insertPair :: Eq a => (a,b) -> [(a,b)] -> [(a,b)]
insertPair (a,b) [] = [(a,b)]
insertPair (a,b) ((c,d):xs) 
 | a == c = (c,b) : xs  -- add xs
 | otherwise = (c,d) : insertPair …  -- todo: recurse

where you need to fill in the part.

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