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

Time:03-21

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)]

CodePudding user response:

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.

  • Related