指定将新对插入到键值对列表中的函数。如果要插入的键已经在列表中,则相应的值将被覆盖,如果没有,则将该对追加到列表的末尾。它不适用于第二种情况。有人能帮我修复我的代码吗?
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)]
发布于 2022-03-20 15:26:37
第三种情况没有任何意义:仍然有可能在列表xs
的其余部分中进一步出现密钥。因此,你应该重新考虑一下这份清单。第二种情况还应该添加xs
作为尾:剩余元素的列表:
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
您需要在其中填写…
部分。
https://stackoverflow.com/questions/71548026
复制相似问题