簡體   English   中英

如何修復我的 inserPair haskell 代碼以適用於所有測試?

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

指定將新對插入鍵值對列表的 function。 如果要插入的鍵已經在列表中,則相應的值將被覆蓋,否則,該對將附加到列表的末尾。 它不適用於案例 2。任何人都可以幫助我在那里更改我的代碼以修復我的代碼嗎?

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

第三種情況沒有意義:密鑰仍然有可能進一步出現在列表xs的 rest 中。 因此,您應該在該列表上遞歸。 第二種情況也應該添加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

您需要填寫部分的地方。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM