指定將新對插入鍵值對串列的函式。如果要插入的鍵已經在串列中,則對應的值將被覆寫,否則,該對將被追加到串列的末尾。它不適用于案例 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)]
uj5u.com熱心網友回復:
第三種情況沒有意義:key 仍然有可能出現在 list 的其余部分中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://www.uj5u.com/net/445997.html
上一篇:HaskellRSA加密
